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\User;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Crypto;
19 use Friendica\Content\Text\BBCode;
20 use Friendica\Content\Text\HTML;
21 use Friendica\Network\Probe;
24 * @brief ActivityPub Protocol class
25 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
26 * https://www.w3.org/TR/activitypub/
27 * https://www.w3.org/TR/activitystreams-core/
28 * https://www.w3.org/TR/activitystreams-vocabulary/
30 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
31 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
33 * Digest: https://tools.ietf.org/html/rfc5843
34 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
36 * Part of the code for HTTP signing is taken from the Osada project.
37 * https://framagit.org/macgirvin/osada
42 * - Activities: Dislike, Update, Delete
43 * - Object Types: Person, Tombstome
46 * - Activities: Like, Dislike, Update, Delete
47 * - Object Tyoes: Article, Announce, Person, Tombstone
50 * - Message distribution
51 * - Endpoints: Outbox, Object, Follower, Following
56 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
58 public static function isRequest()
60 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
61 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
64 public static function transmit($data, $target, $uid)
66 $owner = User::getOwnerDataById($uid);
72 $content = json_encode($data);
74 // Header data that is about to be signed.
75 $host = parse_url($target, PHP_URL_HOST);
76 $path = parse_url($target, PHP_URL_PATH);
77 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
78 $content_length = strlen($content);
80 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
82 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
84 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
86 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
88 $headers[] = 'Content-Type: application/activity+json';
90 Network::post($target, $content, $headers);
91 $return_code = BaseObject::getApp()->get_curl_code();
93 logger('Transmit to ' . $target . ' returned ' . $return_code);
97 * Return the ActivityPub profile of the given user
99 * @param integer $uid User ID
102 public static function profile($uid)
104 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application', 'page-flags'];
105 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
106 'account_removed' => false, 'verified' => true];
107 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
108 $user = DBA::selectFirst('user', $fields, $condition);
109 if (!DBA::isResult($user)) {
113 $fields = ['locality', 'region', 'country-name'];
114 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
115 if (!DBA::isResult($profile)) {
119 $fields = ['name', 'url', 'location', 'about', 'avatar'];
120 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
121 if (!DBA::isResult($contact)) {
125 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
126 ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
127 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
128 'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
130 $data['id'] = $contact['url'];
131 $data['uuid'] = $user['guid'];
132 $data['type'] = $accounttype[$user['account-type']];
133 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
134 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
135 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
136 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
137 $data['preferredUsername'] = $user['nickname'];
138 $data['name'] = $contact['name'];
139 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
140 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
141 $data['summary'] = $contact['about'];
142 $data['url'] = $contact['url'];
143 $data['manuallyApprovesFollowers'] = in_array($profile['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
144 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
145 'owner' => $contact['url'],
146 'publicKeyPem' => $user['pubkey']];
147 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
148 $data['icon'] = ['type' => 'Image',
149 'url' => $contact['avatar']];
151 // tags: https://kitty.town/@inmysocks/100656097926961126.json
155 public static function createActivityFromItem($item_id)
157 $item = Item::selectFirst([], ['id' => $item_id]);
159 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
160 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
161 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
162 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
163 'toot' => 'http://joinmastodon.org/ns#']]];
165 $data['type'] = 'Create';
166 $data['id'] = $item['uri'] . '/activity';
167 $data['actor'] = $item['author-link'];
168 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
169 $data['object'] = self::createNote($item);
173 public static function createNote($item)
176 $data['type'] = 'Note';
177 $data['id'] = $item['uri'];
179 if ($item['uri'] != $item['thr-parent']) {
180 $data['inReplyTo'] = $item['thr-parent'];
183 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
184 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
185 $conversation_uri = $conversation['conversation-uri'];
187 $conversation_uri = $item['parent-uri'];
190 $data['context'] = $data['conversation'] = $conversation_uri;
191 $data['actor'] = $item['author-link'];
192 if (!$item['private']) {
193 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
195 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
196 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
197 $data['attributedTo'] = $item['author-link'];
198 $data['name'] = BBCode::convert($item['title'], false, 7);
199 $data['content'] = BBCode::convert($item['body'], false, 7);
200 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
201 //$data['summary'] = ''; // Ignore by now
202 //$data['sensitive'] = false; // - Query NSFW
203 //$data['emoji'] = []; // Ignore by now
204 //$data['tag'] = []; /// @ToDo
205 //$data['attachment'] = []; // @ToDo
209 public static function transmitActivity($activity, $target, $uid)
211 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
213 $owner = User::getOwnerDataById($uid);
215 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
216 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
218 'actor' => $owner['url'],
219 'object' => $profile['url'],
220 'to' => $profile['url']];
222 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
223 return self::transmit($data, $profile['notify'], $uid);
226 public static function transmitContactAccept($target, $id, $uid)
228 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
230 $owner = User::getOwnerDataById($uid);
231 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
232 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
234 'actor' => $owner['url'],
235 'object' => ['id' => $id, 'type' => 'Follow',
236 'actor' => $profile['url'],
237 'object' => $owner['url']],
238 'to' => $profile['url']];
240 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
241 return self::transmit($data, $profile['notify'], $uid);
244 public static function transmitContactReject($target, $id, $uid)
246 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
248 $owner = User::getOwnerDataById($uid);
249 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
250 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
252 'actor' => $owner['url'],
253 'object' => ['id' => $id, 'type' => 'Follow',
254 'actor' => $profile['url'],
255 'object' => $owner['url']],
256 'to' => $profile['url']];
258 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
259 return self::transmit($data, $profile['notify'], $uid);
262 public static function transmitContactUndo($target, $uid)
264 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
266 $id = System::baseUrl() . '/activity/' . System::createGUID();
268 $owner = User::getOwnerDataById($uid);
269 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
272 'actor' => $owner['url'],
273 'object' => ['id' => $id, 'type' => 'Follow',
274 'actor' => $owner['url'],
275 'object' => $profile['url']],
276 'to' => $profile['url']];
278 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
279 return self::transmit($data, $profile['notify'], $uid);
283 * Fetches ActivityPub content from the given url
285 * @param string $url content url
288 public static function fetchContent($url)
290 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
291 if (!$ret['success'] || empty($ret['body'])) {
295 return json_decode($ret['body'], true);
299 * Resolves the profile url from the address by using webfinger
301 * @param string $addr profile address (user@domain.tld)
304 private static function addrToUrl($addr)
306 $addr_parts = explode('@', $addr);
307 if (count($addr_parts) != 2) {
311 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
313 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
314 if (!$ret['success'] || empty($ret['body'])) {
318 $data = json_decode($ret['body'], true);
320 if (empty($data['links'])) {
324 foreach ($data['links'] as $link) {
325 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
329 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
330 return $link['href'];
337 public static function verifySignature($content, $http_headers)
339 $object = json_decode($content, true);
341 if (empty($object)) {
345 $actor = self::processElement($object, 'actor', 'id');
348 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
350 // First take every header
351 foreach ($http_headers as $k => $v) {
352 $field = str_replace('_', '-', strtolower($k));
353 $headers[$field] = $v;
356 // Now add every http header
357 foreach ($http_headers as $k => $v) {
358 if (strpos($k, 'HTTP_') === 0) {
359 $field = str_replace('_', '-', strtolower(substr($k, 5)));
360 $headers[$field] = $v;
364 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
366 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
371 foreach ($sig_block['headers'] as $h) {
372 if (array_key_exists($h, $headers)) {
373 $signed_data .= $h . ': ' . $headers[$h] . "\n";
376 $signed_data = rtrim($signed_data, "\n");
378 if (empty($signed_data)) {
384 if ($sig_block['algorithm'] === 'rsa-sha256') {
385 $algorithm = 'sha256';
388 if ($sig_block['algorithm'] === 'rsa-sha512') {
389 $algorithm = 'sha512';
392 if (empty($algorithm)) {
396 $key = self::fetchKey($sig_block['keyId'], $actor);
402 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
406 // Check the digest when it is part of the signed data
407 if (in_array('digest', $sig_block['headers'])) {
408 $digest = explode('=', $headers['digest'], 2);
409 if ($digest[0] === 'SHA-256') {
412 if ($digest[0] === 'SHA-512') {
416 /// @todo add all hashes from the rfc
418 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
423 // Check the content-length when it is part of the signed data
424 if (in_array('content-length', $sig_block['headers'])) {
425 if (strlen($content) != $headers['content-length']) {
434 private static function fetchKey($id, $actor)
436 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
438 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
439 if (!empty($profile)) {
440 return $profile['pubkey'];
441 } elseif ($url != $actor) {
442 $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
443 if (!empty($profile)) {
444 return $profile['pubkey'];
454 * @param string $header
455 * @return array associate array with
456 * - \e string \b keyID
457 * - \e string \b algorithm
458 * - \e array \b headers
459 * - \e string \b signature
461 private static function parseSigHeader($header)
466 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
467 $ret['keyId'] = $matches[1];
470 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
471 $ret['algorithm'] = $matches[1];
474 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
475 $ret['headers'] = explode(' ', $matches[1]);
478 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
479 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
486 * Fetches a profile from the given url
488 * @param string $url profile url
491 public static function fetchProfile($url)
493 if (empty(parse_url($url, PHP_URL_SCHEME))) {
494 $url = self::addrToUrl($url);
500 $data = self::fetchContent($url);
502 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
506 $profile = ['network' => Protocol::ACTIVITYPUB];
507 $profile['nick'] = $data['preferredUsername'];
508 $profile['name'] = defaults($data, 'name', $profile['nick']);
509 $profile['guid'] = defaults($data, 'uuid', null);
510 $profile['url'] = $data['id'];
512 $parts = parse_url($profile['url']);
513 unset($parts['scheme']);
514 unset($parts['path']);
515 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
516 $profile['alias'] = self::processElement($data, 'url', 'href');
517 $profile['photo'] = self::processElement($data, 'icon', 'url');
518 // $profile['community']
519 // $profile['keywords']
520 // $profile['location']
521 $profile['about'] = defaults($data, 'summary', '');
522 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
523 $profile['notify'] = $data['inbox'];
524 $profile['poll'] = $data['outbox'];
525 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
527 // Check if the address is resolvable
528 if (self::addrToUrl($profile['addr']) == $profile['url']) {
529 $parts = parse_url($profile['url']);
530 unset($parts['path']);
531 $profile['baseurl'] = Network::unparseURL($parts);
533 unset($profile['addr']);
536 if ($profile['url'] == $profile['alias']) {
537 unset($profile['alias']);
540 // Remove all "null" fields
541 foreach ($profile as $field => $content) {
542 if (is_null($content)) {
543 unset($profile[$field]);
548 // type, manuallyApprovesFollowers
551 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
553 // Unhandled from Misskey
554 // sharedInbox, isCat
556 // Unhandled from Kroeg
557 // kroeg:blocks, updated
562 public static function processInbox($body, $header, $uid)
564 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
566 if (!self::verifySignature($body, $header)) {
567 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
571 $activity = json_decode($body, true);
573 if (!is_array($activity)) {
574 logger('Invalid body.', LOGGER_DEBUG);
578 self::processActivity($activity, $body, $uid);
581 public static function fetchOutbox($url)
583 $data = self::fetchContent($url);
588 if (!empty($data['orderedItems'])) {
589 $items = $data['orderedItems'];
590 } elseif (!empty($data['first']['orderedItems'])) {
591 $items = $data['first']['orderedItems'];
592 } elseif (!empty($data['first'])) {
593 self::fetchOutbox($data['first']);
599 foreach ($items as $activity) {
600 self::processActivity($activity);
604 private static function prepareObjectData($activity, $uid)
606 $actor = self::processElement($activity, 'actor', 'id');
608 logger('Empty actor', LOGGER_DEBUG);
612 // Fetch all receivers from to, cc, bto and bcc
613 $receivers = self::getReceivers($activity, $actor);
615 // When it is a delivery to a personal inbox we add that user to the receivers
617 $owner = User::getOwnerDataById($uid);
618 $additional = ['uid:' . $uid => $uid];
619 $receivers = array_merge($receivers, $additional);
622 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
624 $public = in_array(0, $receivers);
626 if (is_string($activity['object'])) {
627 $object_url = $activity['object'];
628 } elseif (!empty($activity['object']['id'])) {
629 $object_url = $activity['object']['id'];
631 logger('No object found', LOGGER_DEBUG);
635 // Fetch the content only on activities where this matters
636 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
637 $object_data = self::fetchObject($object_url, $activity['object']);
638 if (empty($object_data)) {
639 logger("Object data couldn't be processed", LOGGER_DEBUG);
642 } elseif ($activity['type'] == 'Accept') {
644 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
645 $object_data['object'] = self::processElement($activity, 'object', 'actor');
646 } elseif ($activity['type'] == 'Undo') {
648 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
649 $object_data['object'] = self::processElement($activity, 'object', 'object');
650 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
651 // Create a mostly empty array out of the activity data (instead of the object).
652 // This way we later don't have to check for the existence of ech individual array element.
653 $object_data = self::processCommonData($activity);
654 $object_data['name'] = $activity['type'];
655 $object_data['author'] = $activity['actor'];
656 $object_data['object'] = $object_url;
657 } elseif ($activity['type'] == 'Follow') {
658 $object_data['id'] = $activity['id'];
659 $object_data['object'] = $object_url;
664 $object_data = self::addActivityFields($object_data, $activity);
666 $object_data['type'] = $activity['type'];
667 $object_data['owner'] = $actor;
668 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
673 private static function processActivity($activity, $body = '', $uid = null)
675 if (empty($activity['type'])) {
676 logger('Empty type', LOGGER_DEBUG);
680 if (empty($activity['object'])) {
681 logger('Empty object', LOGGER_DEBUG);
685 if (empty($activity['actor'])) {
686 logger('Empty actor', LOGGER_DEBUG);
692 // title, atomUri, context_id, statusnetConversationId
695 // context, location, signature;
697 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
699 $object_data = self::prepareObjectData($activity, $uid);
700 if (empty($object_data)) {
701 logger('No object data found', LOGGER_DEBUG);
705 switch ($activity['type']) {
708 self::createItem($object_data, $body);
712 self::likeItem($object_data, $body);
725 self::followUser($object_data);
729 if ($object_data['object_type'] == 'Follow') {
730 self::acceptFollowUser($object_data);
735 if ($object_data['object_type'] == 'Follow') {
736 self::undoFollowUser($object_data);
741 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
746 private static function getReceivers($activity, $actor)
750 if (!empty($actor)) {
751 $data = self::fetchContent($actor);
752 $followers = defaults($data, 'followers', '');
754 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
756 logger('Empty actor', LOGGER_DEBUG);
760 $elements = ['to', 'cc', 'bto', 'bcc'];
761 foreach ($elements as $element) {
762 if (empty($activity[$element])) {
766 // The receiver can be an arror or a string
767 if (is_string($activity[$element])) {
768 $activity[$element] = [$activity[$element]];
771 foreach ($activity[$element] as $receiver) {
772 if ($receiver == self::PUBLIC) {
773 $receivers['uid:0'] = 0;
776 if (($receiver == self::PUBLIC) && !empty($actor)) {
777 // This will most likely catch all OStatus connections to Mastodon
778 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
779 $contacts = DBA::select('contact', ['uid'], $condition);
780 while ($contact = DBA::fetch($contacts)) {
781 if ($contact['uid'] != 0) {
782 $receivers['uid:' . $contact['uid']] = $contact['uid'];
785 DBA::close($contacts);
788 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
789 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
790 'network' => Protocol::ACTIVITYPUB];
791 $contacts = DBA::select('contact', ['uid'], $condition);
792 while ($contact = DBA::fetch($contacts)) {
793 if ($contact['uid'] != 0) {
794 $receivers['uid:' . $contact['uid']] = $contact['uid'];
797 DBA::close($contacts);
801 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
802 $contact = DBA::selectFirst('contact', ['uid'], $condition);
803 if (!DBA::isResult($contact)) {
806 $receivers['uid:' . $contact['uid']] = $contact['uid'];
812 private static function addActivityFields($object_data, $activity)
814 if (!empty($activity['published']) && empty($object_data['published'])) {
815 $object_data['published'] = $activity['published'];
818 if (!empty($activity['updated']) && empty($object_data['updated'])) {
819 $object_data['updated'] = $activity['updated'];
822 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
823 $object_data['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
826 if (!empty($activity['instrument'])) {
827 $object_data['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
832 private static function fetchObject($object_url, $object = [], $public = true)
835 $data = self::fetchContent($object_url);
837 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
842 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
846 if (is_string($data)) {
847 $item = Item::selectFirst([], ['uri' => $data]);
848 if (!DBA::isResult($item)) {
849 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
852 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
853 $data = self::createNote($item);
856 if (empty($data['type'])) {
857 logger('Empty type', LOGGER_DEBUG);
860 $type = $data['type'];
861 logger('Type ' . $type, LOGGER_DEBUG);
864 if (in_array($type, ['Note', 'Article', 'Video'])) {
865 $common = self::processCommonData($data);
870 return array_merge($common, self::processNote($data));
872 return array_merge($common, self::processArticle($data));
874 return array_merge($common, self::processVideo($data));
877 if (empty($data['object'])) {
880 return self::fetchObject($data['object']);
887 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
892 private static function processCommonData(&$object)
894 if (empty($object['id'])) {
899 $object_data['type'] = $object['type'];
900 $object_data['uri'] = $object['id'];
902 if (!empty($object['inReplyTo'])) {
903 $object_data['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
905 $object_data['reply-to-uri'] = $object_data['uri'];
908 $object_data['published'] = defaults($object, 'published', null);
909 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
911 if (empty($object_data['published']) && !empty($object_data['updated'])) {
912 $object_data['published'] = $object_data['updated'];
915 $object_data['uuid'] = defaults($object, 'uuid', null);
916 $object_data['owner'] = $object_data['author'] = self::processElement($object, 'attributedTo', 'id');
917 $object_data['context'] = defaults($object, 'context', null);
918 $object_data['conversation'] = defaults($object, 'conversation', null);
919 $object_data['sensitive'] = defaults($object, 'sensitive', null);
920 $object_data['name'] = defaults($object, 'title', null);
921 $object_data['name'] = defaults($object, 'name', $object_data['name']);
922 $object_data['summary'] = defaults($object, 'summary', null);
923 $object_data['content'] = defaults($object, 'content', null);
924 $object_data['source'] = defaults($object, 'source', null);
925 $object_data['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
926 $object_data['attachments'] = defaults($object, 'attachment', null);
927 $object_data['tags'] = defaults($object, 'tag', null);
928 $object_data['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
929 $object_data['alternate-url'] = self::processElement($object, 'url', 'href');
930 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
933 // @context, type, actor, signature, mediaType, duration, replies, icon
935 // Also missing: (Defined in the standard, but currently unused)
936 // audience, preview, endTime, startTime, generator, image
941 private static function processNote($object)
946 // emoji, atomUri, inReplyToAtomUri
949 // contentMap, announcement_count, announcements, context_id, likes, like_count
950 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
955 private static function processArticle($object)
962 private static function processVideo($object)
967 // category, licence, language, commentsEnabled
970 // views, waitTranscoding, state, support, subtitleLanguage
971 // likes, dislikes, shares, comments
976 private static function processElement($array, $element, $key, $type = null, $type_value = null)
982 if (empty($array[$element])) {
986 if (is_string($array[$element])) {
987 return $array[$element];
990 if (is_null($type_value)) {
991 if (!empty($array[$element][$key])) {
992 return $array[$element][$key];
995 if (!empty($array[$element][0][$key])) {
996 return $array[$element][0][$key];
1002 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
1003 return $array[$element][$key];
1006 /// @todo Add array search
1011 private static function convertMentions($body)
1013 $URLSearchString = "^\[\]";
1014 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1019 private static function constructTagList($tags, $sensitive)
1026 foreach ($tags as $tag) {
1027 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1028 if (!empty($tag_text)) {
1032 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1036 /// @todo add nsfw for $sensitive
1041 private static function constructAttachList($attachments, $item)
1043 if (empty($attachments)) {
1047 foreach ($attachments as $attach) {
1048 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1049 if ($filetype == 'image') {
1050 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1052 if (!empty($item["attach"])) {
1053 $item["attach"] .= ',';
1055 $item["attach"] = '';
1057 if (!isset($attach['length'])) {
1058 $attach['length'] = "0";
1060 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1067 private static function createItem($activity, $body)
1070 $item['verb'] = ACTIVITY_POST;
1071 $item['parent-uri'] = $activity['reply-to-uri'];
1073 if ($activity['reply-to-uri'] == $activity['uri']) {
1074 $item['gravity'] = GRAVITY_PARENT;
1075 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1077 $item['gravity'] = GRAVITY_COMMENT;
1078 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1081 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1082 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1083 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1086 self::postItem($activity, $item, $body);
1089 private static function likeItem($activity, $body)
1092 $item['verb'] = ACTIVITY_LIKE;
1093 $item['parent-uri'] = $activity['object'];
1094 $item['gravity'] = GRAVITY_ACTIVITY;
1095 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1097 self::postItem($activity, $item, $body);
1100 private static function postItem($activity, $item, $body)
1102 /// @todo What to do with $activity['context']?
1104 $item['network'] = Protocol::ACTIVITYPUB;
1105 $item['private'] = !in_array(0, $activity['receiver']);
1106 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1107 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1108 $item['uri'] = $activity['uri'];
1109 $item['created'] = $activity['published'];
1110 $item['edited'] = $activity['updated'];
1111 $item['guid'] = $activity['uuid'];
1112 $item['title'] = HTML::toBBCode($activity['name']);
1113 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1114 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1115 $item['location'] = $activity['location'];
1116 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1117 $item['app'] = $activity['service'];
1118 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1120 $item = self::constructAttachList($activity['attachments'], $item);
1122 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1123 if (!empty($source)) {
1124 $item['body'] = $source;
1127 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1128 $item['source'] = $body;
1129 $item['conversation-uri'] = $activity['conversation'];
1131 foreach ($activity['receiver'] as $receiver) {
1132 $item['uid'] = $receiver;
1133 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1135 if (($receiver != 0) && empty($item['contact-id'])) {
1136 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1139 $item_id = Item::insert($item);
1140 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1144 private static function fetchMissingActivity($url, $child)
1146 $object = ActivityPub::fetchContent($url);
1147 if (empty($object)) {
1148 logger('Activity ' . $url . ' was not fetchable, aborting.');
1153 $activity['@context'] = $object['@context'];
1154 unset($object['@context']);
1155 $activity['id'] = $object['id'];
1156 $activity['to'] = defaults($object, 'to', []);
1157 $activity['cc'] = defaults($object, 'cc', []);
1158 $activity['actor'] = $activity['author'];
1159 $activity['object'] = $object;
1160 $activity['published'] = $object['published'];
1161 $activity['type'] = 'Create';
1162 self::processActivity($activity);
1163 logger('Activity ' . $url . ' had been fetched and processed.');
1166 private static function getUserOfObject($object)
1168 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1169 if (!DBA::isResult($self)) {
1172 return $self['uid'];
1176 private static function followUser($activity)
1178 $uid = self::getUserOfObject($activity['object']);
1183 $owner = User::getOwnerDataById($uid);
1185 $cid = Contact::getIdForURL($activity['owner'], $uid);
1187 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1192 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1193 'author-link' => $activity['owner']];
1195 Contact::addRelationship($owner, $contact, $item);
1196 $cid = Contact::getIdForURL($activity['owner'], $uid);
1201 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1202 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1203 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1206 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1207 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1210 private static function acceptFollowUser($activity)
1212 $uid = self::getUserOfObject($activity['object']);
1217 $owner = User::getOwnerDataById($uid);
1219 $cid = Contact::getIdForURL($activity['owner'], $uid);
1221 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1225 $fields = ['pending' => false];
1227 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1228 if ($contact['rel'] == Contact::FOLLOWER) {
1229 $fields['rel'] = Contact::FRIEND;
1232 $condition = ['id' => $cid];
1233 DBA::update('contact', $fields, $condition);
1234 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1237 private static function undoFollowUser($activity)
1239 $uid = self::getUserOfObject($activity['object']);
1244 $owner = User::getOwnerDataById($uid);
1246 $cid = Contact::getIdForURL($activity['owner'], $uid);
1248 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1252 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1253 if (!DBA::isResult($contact)) {
1257 Contact::removeFollower($owner, $contact);
1258 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);