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
35 * https://github.com/digitalbazaar/php-json-ld
37 * Part of the code for HTTP signing is taken from the Osada project.
38 * https://framagit.org/macgirvin/osada
43 * - Activities: Dislike, Update, Delete
44 * - Object Types: Person, Tombstome
47 * - Activities: Like, Dislike, Update, Delete
48 * - Object Tyoes: Article, Announce, Person, Tombstone
51 * - Message distribution
52 * - Endpoints: Outbox, Object, Follower, Following
57 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
59 public static function isRequest()
61 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
62 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
65 public static function transmit($data, $target, $uid)
67 $owner = User::getOwnerDataById($uid);
73 $content = json_encode($data);
75 // Header data that is about to be signed.
76 $host = parse_url($target, PHP_URL_HOST);
77 $path = parse_url($target, PHP_URL_PATH);
78 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
79 $content_length = strlen($content);
81 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
83 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
85 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
87 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
89 $headers[] = 'Content-Type: application/activity+json';
91 Network::post($target, $content, $headers);
92 $return_code = BaseObject::getApp()->get_curl_code();
94 logger('Transmit to ' . $target . ' returned ' . $return_code);
98 * Return the ActivityPub profile of the given user
100 * @param integer $uid User ID
103 public static function profile($uid)
105 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application', 'page-flags'];
106 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
107 'account_removed' => false, 'verified' => true];
108 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
109 $user = DBA::selectFirst('user', $fields, $condition);
110 if (!DBA::isResult($user)) {
114 $fields = ['locality', 'region', 'country-name'];
115 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
116 if (!DBA::isResult($profile)) {
120 $fields = ['name', 'url', 'location', 'about', 'avatar'];
121 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
122 if (!DBA::isResult($contact)) {
126 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
127 ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
128 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
129 'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
131 $data['id'] = $contact['url'];
132 $data['uuid'] = $user['guid'];
133 $data['type'] = $accounttype[$user['account-type']];
134 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
135 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
136 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
137 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
138 $data['preferredUsername'] = $user['nickname'];
139 $data['name'] = $contact['name'];
140 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
141 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
142 $data['summary'] = $contact['about'];
143 $data['url'] = $contact['url'];
144 $data['manuallyApprovesFollowers'] = in_array($profile['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
145 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
146 'owner' => $contact['url'],
147 'publicKeyPem' => $user['pubkey']];
148 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
149 $data['icon'] = ['type' => 'Image',
150 'url' => $contact['avatar']];
152 // tags: https://kitty.town/@inmysocks/100656097926961126.json
156 public static function createActivityFromItem($item_id)
158 $item = Item::selectFirst([], ['id' => $item_id]);
160 if (!DBA::isResult($item)) {
164 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
165 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
166 if (DBA::isResult($conversation)) {
167 $data = json_decode($conversation['source']);
173 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
174 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
175 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
176 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
177 'toot' => 'http://joinmastodon.org/ns#']]];
179 $data['type'] = 'Create';
180 $data['id'] = $item['uri'] . '/activity';
181 $data['actor'] = $item['author-link'];
182 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
183 $data['object'] = self::createNote($item);
187 public static function createNote($item)
190 $data['type'] = 'Note';
191 $data['id'] = $item['uri'];
193 if ($item['uri'] != $item['thr-parent']) {
194 $data['inReplyTo'] = $item['thr-parent'];
197 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
198 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
199 $conversation_uri = $conversation['conversation-uri'];
201 $conversation_uri = $item['parent-uri'];
204 $data['context'] = $data['conversation'] = $conversation_uri;
205 $data['actor'] = $item['author-link'];
206 if (!$item['private']) {
207 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
209 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
210 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
211 $data['attributedTo'] = $item['author-link'];
212 $data['name'] = BBCode::convert($item['title'], false, 7);
213 $data['content'] = BBCode::convert($item['body'], false, 7);
214 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
215 //$data['summary'] = ''; // Ignore by now
216 //$data['sensitive'] = false; // - Query NSFW
217 //$data['emoji'] = []; // Ignore by now
218 //$data['tag'] = []; /// @ToDo
219 //$data['attachment'] = []; // @ToDo
223 public static function transmitActivity($activity, $target, $uid)
225 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
227 $owner = User::getOwnerDataById($uid);
229 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
230 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
232 'actor' => $owner['url'],
233 'object' => $profile['url'],
234 'to' => $profile['url']];
236 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
237 return self::transmit($data, $profile['notify'], $uid);
240 public static function transmitContactAccept($target, $id, $uid)
242 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
244 $owner = User::getOwnerDataById($uid);
245 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
246 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
248 'actor' => $owner['url'],
249 'object' => ['id' => $id, 'type' => 'Follow',
250 'actor' => $profile['url'],
251 'object' => $owner['url']],
252 'to' => $profile['url']];
254 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
255 return self::transmit($data, $profile['notify'], $uid);
258 public static function transmitContactReject($target, $id, $uid)
260 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
262 $owner = User::getOwnerDataById($uid);
263 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
264 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
266 'actor' => $owner['url'],
267 'object' => ['id' => $id, 'type' => 'Follow',
268 'actor' => $profile['url'],
269 'object' => $owner['url']],
270 'to' => $profile['url']];
272 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
273 return self::transmit($data, $profile['notify'], $uid);
276 public static function transmitContactUndo($target, $uid)
278 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
280 $id = System::baseUrl() . '/activity/' . System::createGUID();
282 $owner = User::getOwnerDataById($uid);
283 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
286 'actor' => $owner['url'],
287 'object' => ['id' => $id, 'type' => 'Follow',
288 'actor' => $owner['url'],
289 'object' => $profile['url']],
290 'to' => $profile['url']];
292 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
293 return self::transmit($data, $profile['notify'], $uid);
297 * Fetches ActivityPub content from the given url
299 * @param string $url content url
302 public static function fetchContent($url)
304 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
305 if (!$ret['success'] || empty($ret['body'])) {
309 return json_decode($ret['body'], true);
313 * Resolves the profile url from the address by using webfinger
315 * @param string $addr profile address (user@domain.tld)
318 private static function addrToUrl($addr)
320 $addr_parts = explode('@', $addr);
321 if (count($addr_parts) != 2) {
325 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
327 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
328 if (!$ret['success'] || empty($ret['body'])) {
332 $data = json_decode($ret['body'], true);
334 if (empty($data['links'])) {
338 foreach ($data['links'] as $link) {
339 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
343 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
344 return $link['href'];
351 public static function verifySignature($content, $http_headers)
353 $object = json_decode($content, true);
355 if (empty($object)) {
359 $actor = self::processElement($object, 'actor', 'id');
362 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
364 // First take every header
365 foreach ($http_headers as $k => $v) {
366 $field = str_replace('_', '-', strtolower($k));
367 $headers[$field] = $v;
370 // Now add every http header
371 foreach ($http_headers as $k => $v) {
372 if (strpos($k, 'HTTP_') === 0) {
373 $field = str_replace('_', '-', strtolower(substr($k, 5)));
374 $headers[$field] = $v;
378 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
380 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
385 foreach ($sig_block['headers'] as $h) {
386 if (array_key_exists($h, $headers)) {
387 $signed_data .= $h . ': ' . $headers[$h] . "\n";
390 $signed_data = rtrim($signed_data, "\n");
392 if (empty($signed_data)) {
398 if ($sig_block['algorithm'] === 'rsa-sha256') {
399 $algorithm = 'sha256';
402 if ($sig_block['algorithm'] === 'rsa-sha512') {
403 $algorithm = 'sha512';
406 if (empty($algorithm)) {
410 $key = self::fetchKey($sig_block['keyId'], $actor);
416 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
420 // Check the digest when it is part of the signed data
421 if (in_array('digest', $sig_block['headers'])) {
422 $digest = explode('=', $headers['digest'], 2);
423 if ($digest[0] === 'SHA-256') {
426 if ($digest[0] === 'SHA-512') {
430 /// @todo add all hashes from the rfc
432 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
437 // Check the content-length when it is part of the signed data
438 if (in_array('content-length', $sig_block['headers'])) {
439 if (strlen($content) != $headers['content-length']) {
448 private static function fetchKey($id, $actor)
450 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
452 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
453 if (!empty($profile)) {
454 return $profile['pubkey'];
455 } elseif ($url != $actor) {
456 $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
457 if (!empty($profile)) {
458 return $profile['pubkey'];
468 * @param string $header
469 * @return array associate array with
470 * - \e string \b keyID
471 * - \e string \b algorithm
472 * - \e array \b headers
473 * - \e string \b signature
475 private static function parseSigHeader($header)
480 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
481 $ret['keyId'] = $matches[1];
484 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
485 $ret['algorithm'] = $matches[1];
488 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
489 $ret['headers'] = explode(' ', $matches[1]);
492 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
493 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
500 * Fetches a profile from the given url
502 * @param string $url profile url
505 public static function fetchProfile($url)
507 if (empty(parse_url($url, PHP_URL_SCHEME))) {
508 $url = self::addrToUrl($url);
514 $data = self::fetchContent($url);
516 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
520 $profile = ['network' => Protocol::ACTIVITYPUB];
521 $profile['nick'] = $data['preferredUsername'];
522 $profile['name'] = defaults($data, 'name', $profile['nick']);
523 $profile['guid'] = defaults($data, 'uuid', null);
524 $profile['url'] = $data['id'];
526 $parts = parse_url($profile['url']);
527 unset($parts['scheme']);
528 unset($parts['path']);
529 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
530 $profile['alias'] = self::processElement($data, 'url', 'href');
531 $profile['photo'] = self::processElement($data, 'icon', 'url');
532 // $profile['community']
533 // $profile['keywords']
534 // $profile['location']
535 $profile['about'] = defaults($data, 'summary', '');
536 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
537 $profile['notify'] = $data['inbox'];
538 $profile['poll'] = $data['outbox'];
539 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
541 // Check if the address is resolvable
542 if (self::addrToUrl($profile['addr']) == $profile['url']) {
543 $parts = parse_url($profile['url']);
544 unset($parts['path']);
545 $profile['baseurl'] = Network::unparseURL($parts);
547 unset($profile['addr']);
550 if ($profile['url'] == $profile['alias']) {
551 unset($profile['alias']);
554 // Remove all "null" fields
555 foreach ($profile as $field => $content) {
556 if (is_null($content)) {
557 unset($profile[$field]);
562 // type, manuallyApprovesFollowers
565 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
567 // Unhandled from Misskey
568 // sharedInbox, isCat
570 // Unhandled from Kroeg
571 // kroeg:blocks, updated
576 public static function processInbox($body, $header, $uid)
578 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
580 if (!self::verifySignature($body, $header)) {
581 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
585 $activity = json_decode($body, true);
587 if (!is_array($activity)) {
588 logger('Invalid body.', LOGGER_DEBUG);
592 self::processActivity($activity, $body, $uid);
595 public static function fetchOutbox($url)
597 $data = self::fetchContent($url);
602 if (!empty($data['orderedItems'])) {
603 $items = $data['orderedItems'];
604 } elseif (!empty($data['first']['orderedItems'])) {
605 $items = $data['first']['orderedItems'];
606 } elseif (!empty($data['first'])) {
607 self::fetchOutbox($data['first']);
613 foreach ($items as $activity) {
614 self::processActivity($activity);
618 private static function prepareObjectData($activity, $uid)
620 $actor = self::processElement($activity, 'actor', 'id');
622 logger('Empty actor', LOGGER_DEBUG);
626 // Fetch all receivers from to, cc, bto and bcc
627 $receivers = self::getReceivers($activity, $actor);
629 // When it is a delivery to a personal inbox we add that user to the receivers
631 $owner = User::getOwnerDataById($uid);
632 $additional = ['uid:' . $uid => $uid];
633 $receivers = array_merge($receivers, $additional);
636 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
638 $public = in_array(0, $receivers);
640 if (is_string($activity['object'])) {
641 $object_url = $activity['object'];
642 } elseif (!empty($activity['object']['id'])) {
643 $object_url = $activity['object']['id'];
645 logger('No object found', LOGGER_DEBUG);
649 // Fetch the content only on activities where this matters
650 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
651 $object_data = self::fetchObject($object_url, $activity['object']);
652 if (empty($object_data)) {
653 logger("Object data couldn't be processed", LOGGER_DEBUG);
656 } elseif ($activity['type'] == 'Accept') {
658 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
659 $object_data['object'] = self::processElement($activity, 'object', 'actor');
660 } elseif ($activity['type'] == 'Undo') {
662 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
663 $object_data['object'] = self::processElement($activity, 'object', 'object');
664 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
665 // Create a mostly empty array out of the activity data (instead of the object).
666 // This way we later don't have to check for the existence of ech individual array element.
667 $object_data = self::processCommonData($activity);
668 $object_data['name'] = $activity['type'];
669 $object_data['author'] = $activity['actor'];
670 $object_data['object'] = $object_url;
671 } elseif ($activity['type'] == 'Follow') {
672 $object_data['id'] = $activity['id'];
673 $object_data['object'] = $object_url;
678 $object_data = self::addActivityFields($object_data, $activity);
680 $object_data['type'] = $activity['type'];
681 $object_data['owner'] = $actor;
682 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
687 private static function processActivity($activity, $body = '', $uid = null)
689 if (empty($activity['type'])) {
690 logger('Empty type', LOGGER_DEBUG);
694 if (empty($activity['object'])) {
695 logger('Empty object', LOGGER_DEBUG);
699 if (empty($activity['actor'])) {
700 logger('Empty actor', LOGGER_DEBUG);
706 // title, atomUri, context_id, statusnetConversationId
709 // context, location, signature;
711 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
713 $object_data = self::prepareObjectData($activity, $uid);
714 if (empty($object_data)) {
715 logger('No object data found', LOGGER_DEBUG);
719 switch ($activity['type']) {
722 self::createItem($object_data, $body);
726 self::likeItem($object_data, $body);
739 self::followUser($object_data);
743 if ($object_data['object_type'] == 'Follow') {
744 self::acceptFollowUser($object_data);
749 if ($object_data['object_type'] == 'Follow') {
750 self::undoFollowUser($object_data);
755 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
760 private static function getReceivers($activity, $actor)
764 if (!empty($actor)) {
765 $data = self::fetchContent($actor);
766 $followers = defaults($data, 'followers', '');
768 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
770 logger('Empty actor', LOGGER_DEBUG);
774 $elements = ['to', 'cc', 'bto', 'bcc'];
775 foreach ($elements as $element) {
776 if (empty($activity[$element])) {
780 // The receiver can be an arror or a string
781 if (is_string($activity[$element])) {
782 $activity[$element] = [$activity[$element]];
785 foreach ($activity[$element] as $receiver) {
786 if ($receiver == self::PUBLIC) {
787 $receivers['uid:0'] = 0;
790 if (($receiver == self::PUBLIC) && !empty($actor)) {
791 // This will most likely catch all OStatus connections to Mastodon
792 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
793 $contacts = DBA::select('contact', ['uid'], $condition);
794 while ($contact = DBA::fetch($contacts)) {
795 if ($contact['uid'] != 0) {
796 $receivers['uid:' . $contact['uid']] = $contact['uid'];
799 DBA::close($contacts);
802 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
803 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
804 'network' => Protocol::ACTIVITYPUB];
805 $contacts = DBA::select('contact', ['uid'], $condition);
806 while ($contact = DBA::fetch($contacts)) {
807 if ($contact['uid'] != 0) {
808 $receivers['uid:' . $contact['uid']] = $contact['uid'];
811 DBA::close($contacts);
815 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
816 $contact = DBA::selectFirst('contact', ['uid'], $condition);
817 if (!DBA::isResult($contact)) {
820 $receivers['uid:' . $contact['uid']] = $contact['uid'];
826 private static function addActivityFields($object_data, $activity)
828 if (!empty($activity['published']) && empty($object_data['published'])) {
829 $object_data['published'] = $activity['published'];
832 if (!empty($activity['updated']) && empty($object_data['updated'])) {
833 $object_data['updated'] = $activity['updated'];
836 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
837 $object_data['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
840 if (!empty($activity['instrument'])) {
841 $object_data['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
846 private static function fetchObject($object_url, $object = [], $public = true)
849 $data = self::fetchContent($object_url);
851 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
856 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
860 if (is_string($data)) {
861 $item = Item::selectFirst([], ['uri' => $data]);
862 if (!DBA::isResult($item)) {
863 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
866 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
867 $data = self::createNote($item);
870 if (empty($data['type'])) {
871 logger('Empty type', LOGGER_DEBUG);
874 $type = $data['type'];
875 logger('Type ' . $type, LOGGER_DEBUG);
878 if (in_array($type, ['Note', 'Article', 'Video'])) {
879 $common = self::processCommonData($data);
884 return array_merge($common, self::processNote($data));
886 return array_merge($common, self::processArticle($data));
888 return array_merge($common, self::processVideo($data));
891 if (empty($data['object'])) {
894 return self::fetchObject($data['object']);
901 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
906 private static function processCommonData(&$object)
908 if (empty($object['id'])) {
913 $object_data['type'] = $object['type'];
914 $object_data['uri'] = $object['id'];
916 if (!empty($object['inReplyTo'])) {
917 $object_data['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
919 $object_data['reply-to-uri'] = $object_data['uri'];
922 $object_data['published'] = defaults($object, 'published', null);
923 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
925 if (empty($object_data['published']) && !empty($object_data['updated'])) {
926 $object_data['published'] = $object_data['updated'];
929 $object_data['uuid'] = defaults($object, 'uuid', null);
930 $object_data['owner'] = $object_data['author'] = self::processElement($object, 'attributedTo', 'id');
931 $object_data['context'] = defaults($object, 'context', null);
932 $object_data['conversation'] = defaults($object, 'conversation', null);
933 $object_data['sensitive'] = defaults($object, 'sensitive', null);
934 $object_data['name'] = defaults($object, 'title', null);
935 $object_data['name'] = defaults($object, 'name', $object_data['name']);
936 $object_data['summary'] = defaults($object, 'summary', null);
937 $object_data['content'] = defaults($object, 'content', null);
938 $object_data['source'] = defaults($object, 'source', null);
939 $object_data['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
940 $object_data['attachments'] = defaults($object, 'attachment', null);
941 $object_data['tags'] = defaults($object, 'tag', null);
942 $object_data['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
943 $object_data['alternate-url'] = self::processElement($object, 'url', 'href');
944 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
947 // @context, type, actor, signature, mediaType, duration, replies, icon
949 // Also missing: (Defined in the standard, but currently unused)
950 // audience, preview, endTime, startTime, generator, image
955 private static function processNote($object)
960 // emoji, atomUri, inReplyToAtomUri
963 // contentMap, announcement_count, announcements, context_id, likes, like_count
964 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
969 private static function processArticle($object)
976 private static function processVideo($object)
981 // category, licence, language, commentsEnabled
984 // views, waitTranscoding, state, support, subtitleLanguage
985 // likes, dislikes, shares, comments
990 private static function processElement($array, $element, $key, $type = null, $type_value = null)
996 if (empty($array[$element])) {
1000 if (is_string($array[$element])) {
1001 return $array[$element];
1004 if (is_null($type_value)) {
1005 if (!empty($array[$element][$key])) {
1006 return $array[$element][$key];
1009 if (!empty($array[$element][0][$key])) {
1010 return $array[$element][0][$key];
1016 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
1017 return $array[$element][$key];
1020 /// @todo Add array search
1025 private static function convertMentions($body)
1027 $URLSearchString = "^\[\]";
1028 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1033 private static function constructTagList($tags, $sensitive)
1040 foreach ($tags as $tag) {
1041 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1042 if (!empty($tag_text)) {
1046 if (empty($tag['href'])) {
1051 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1055 /// @todo add nsfw for $sensitive
1060 private static function constructAttachList($attachments, $item)
1062 if (empty($attachments)) {
1066 foreach ($attachments as $attach) {
1067 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1068 if ($filetype == 'image') {
1069 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1071 if (!empty($item["attach"])) {
1072 $item["attach"] .= ',';
1074 $item["attach"] = '';
1076 if (!isset($attach['length'])) {
1077 $attach['length'] = "0";
1079 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1086 private static function createItem($activity, $body)
1089 $item['verb'] = ACTIVITY_POST;
1090 $item['parent-uri'] = $activity['reply-to-uri'];
1092 if ($activity['reply-to-uri'] == $activity['uri']) {
1093 $item['gravity'] = GRAVITY_PARENT;
1094 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1096 $item['gravity'] = GRAVITY_COMMENT;
1097 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1100 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1101 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1102 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1105 self::postItem($activity, $item, $body);
1108 private static function likeItem($activity, $body)
1111 $item['verb'] = ACTIVITY_LIKE;
1112 $item['parent-uri'] = $activity['object'];
1113 $item['gravity'] = GRAVITY_ACTIVITY;
1114 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1116 self::postItem($activity, $item, $body);
1119 private static function postItem($activity, $item, $body)
1121 /// @todo What to do with $activity['context']?
1123 $item['network'] = Protocol::ACTIVITYPUB;
1124 $item['private'] = !in_array(0, $activity['receiver']);
1125 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1126 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1127 $item['uri'] = $activity['uri'];
1128 $item['created'] = $activity['published'];
1129 $item['edited'] = $activity['updated'];
1130 $item['guid'] = $activity['uuid'];
1131 $item['title'] = HTML::toBBCode($activity['name']);
1132 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1133 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1134 $item['location'] = $activity['location'];
1135 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1136 $item['app'] = $activity['service'];
1137 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1139 $item = self::constructAttachList($activity['attachments'], $item);
1141 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1142 if (!empty($source)) {
1143 $item['body'] = $source;
1146 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1147 $item['source'] = $body;
1148 $item['conversation-uri'] = $activity['conversation'];
1150 foreach ($activity['receiver'] as $receiver) {
1151 $item['uid'] = $receiver;
1152 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1154 if (($receiver != 0) && empty($item['contact-id'])) {
1155 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1158 $item_id = Item::insert($item);
1159 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1163 private static function fetchMissingActivity($url, $child)
1165 $object = ActivityPub::fetchContent($url);
1166 if (empty($object)) {
1167 logger('Activity ' . $url . ' was not fetchable, aborting.');
1172 $activity['@context'] = $object['@context'];
1173 unset($object['@context']);
1174 $activity['id'] = $object['id'];
1175 $activity['to'] = defaults($object, 'to', []);
1176 $activity['cc'] = defaults($object, 'cc', []);
1177 $activity['actor'] = $activity['author'];
1178 $activity['object'] = $object;
1179 $activity['published'] = $object['published'];
1180 $activity['type'] = 'Create';
1181 self::processActivity($activity);
1182 logger('Activity ' . $url . ' had been fetched and processed.');
1185 private static function getUserOfObject($object)
1187 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1188 if (!DBA::isResult($self)) {
1191 return $self['uid'];
1195 private static function followUser($activity)
1197 $uid = self::getUserOfObject($activity['object']);
1202 $owner = User::getOwnerDataById($uid);
1204 $cid = Contact::getIdForURL($activity['owner'], $uid);
1206 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1211 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1212 'author-link' => $activity['owner']];
1214 Contact::addRelationship($owner, $contact, $item);
1215 $cid = Contact::getIdForURL($activity['owner'], $uid);
1220 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1221 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1222 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1225 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1226 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1229 private static function acceptFollowUser($activity)
1231 $uid = self::getUserOfObject($activity['object']);
1236 $owner = User::getOwnerDataById($uid);
1238 $cid = Contact::getIdForURL($activity['owner'], $uid);
1240 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1244 $fields = ['pending' => false];
1246 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1247 if ($contact['rel'] == Contact::FOLLOWER) {
1248 $fields['rel'] = Contact::FRIEND;
1251 $condition = ['id' => $cid];
1252 DBA::update('contact', $fields, $condition);
1253 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1256 private static function undoFollowUser($activity)
1258 $uid = self::getUserOfObject($activity['object']);
1263 $owner = User::getOwnerDataById($uid);
1265 $cid = Contact::getIdForURL($activity['owner'], $uid);
1267 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1271 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1272 if (!DBA::isResult($contact)) {
1276 Contact::removeFollower($owner, $contact);
1277 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);