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\Util\JsonLD;
23 use Friendica\Util\LDSignature;
26 * @brief ActivityPub Protocol class
27 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
28 * https://www.w3.org/TR/activitypub/
29 * https://www.w3.org/TR/activitystreams-core/
30 * https://www.w3.org/TR/activitystreams-vocabulary/
32 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
33 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
35 * Digest: https://tools.ietf.org/html/rfc5843
36 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
37 * https://github.com/digitalbazaar/php-json-ld
39 * Part of the code for HTTP signing is taken from the Osada project.
40 * https://framagit.org/macgirvin/osada
45 * - Activities: Update, Delete (Activities/Notes)
46 * - Object Types: Person, Tombstome
49 * - Activities: Announce, Delete Notes
50 * - Object Tyoes: Person, Tombstone
53 * - Endpoints: Outbox, Follower, Following
55 * - Queueing unsucessful deliveries
59 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
61 public static function isRequest()
63 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
64 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
68 * Return the ActivityPub profile of the given user
70 * @param integer $uid User ID
73 public static function profile($uid)
75 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
76 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
77 'account_removed' => false, 'verified' => true];
78 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
79 $user = DBA::selectFirst('user', $fields, $condition);
80 if (!DBA::isResult($user)) {
84 $fields = ['locality', 'region', 'country-name'];
85 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
86 if (!DBA::isResult($profile)) {
90 $fields = ['name', 'url', 'location', 'about', 'avatar'];
91 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
92 if (!DBA::isResult($contact)) {
96 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
97 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
98 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
100 $data['id'] = $contact['url'];
101 $data['uuid'] = $user['guid'];
102 $data['type'] = $accounttype[$user['account-type']];
103 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
104 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
105 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
106 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
107 $data['preferredUsername'] = $user['nickname'];
108 $data['name'] = $contact['name'];
109 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
110 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
111 $data['summary'] = $contact['about'];
112 $data['url'] = $contact['url'];
113 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
114 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
115 'owner' => $contact['url'],
116 'publicKeyPem' => $user['pubkey']];
117 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
118 $data['icon'] = ['type' => 'Image',
119 'url' => $contact['avatar']];
121 // tags: https://kitty.town/@inmysocks/100656097926961126.json
125 private static function fetchPermissionBlockFromConversation($item)
127 if (empty($item['thr-parent'])) {
131 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
132 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
133 if (!DBA::isResult($conversation)) {
137 $activity = json_decode($conversation['source'], true);
139 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
140 $profile = ActivityPub::fetchprofile($actor);
142 $item_profile = ActivityPub::fetchprofile($item['author-link']);
143 $exclude[] = $item['author-link'];
145 if ($item['gravity'] == GRAVITY_PARENT) {
146 $exclude[] = $item['owner-link'];
151 $elements = ['to', 'cc', 'bto', 'bcc'];
152 foreach ($elements as $element) {
153 if (empty($activity[$element])) {
156 if (is_string($activity[$element])) {
157 $activity[$element] = [$activity[$element]];
159 foreach ($activity[$element] as $receiver) {
160 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
161 $receiver = $item_profile['followers'];
163 if (!in_array($receiver, $exclude)) {
164 $permissions[$element][] = $receiver;
171 public static function createPermissionBlockForItem($item)
173 $data = ['to' => [], 'cc' => []];
175 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
177 $actor_profile = ActivityPub::fetchprofile($item['author-link']);
179 $terms = Term::tagArrayFromItemId($item['id']);
181 $contacts[$item['author-link']] = $item['author-link'];
183 if (!$item['private']) {
184 $data['to'][] = self::PUBLIC;
185 if (!empty($actor_profile['followers'])) {
186 $data['cc'][] = $actor_profile['followers'];
189 foreach ($terms as $term) {
190 if ($term['type'] != TERM_MENTION) {
193 $profile = self::fetchprofile($term['url']);
194 if (!empty($profile) && empty($contacts[$profile['url']])) {
195 $data['cc'][] = $profile['url'];
196 $contacts[$profile['url']] = $profile['url'];
200 $receiver_list = Item::enumeratePermissions($item);
204 foreach ($terms as $term) {
205 if ($term['type'] != TERM_MENTION) {
208 $cid = Contact::getIdForURL($term['url'], $item['uid']);
209 if (!empty($cid) && in_array($cid, $receiver_list)) {
210 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
211 $data['to'][] = $contact['url'];
212 $contacts[$contact['url']] = $contact['url'];
216 foreach ($receiver_list as $receiver) {
217 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
218 if (empty($contacts[$contact['url']])) {
219 $data['cc'][] = $contact['url'];
220 $contacts[$contact['url']] = $contact['url'];
225 $parents = Item::select(['author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
226 while ($parent = Item::fetch($parents)) {
227 $profile = self::fetchprofile($parent['author-link']);
228 if (!empty($profile) && empty($contacts[$profile['url']])) {
229 $data['cc'][] = $profile['url'];
230 $contacts[$profile['url']] = $profile['url'];
233 if ($item['gravity'] != GRAVITY_PARENT) {
237 $profile = self::fetchprofile($parent['owner-link']);
238 if (!empty($profile) && empty($contacts[$profile['url']])) {
239 $data['cc'][] = $profile['url'];
240 $contacts[$profile['url']] = $profile['url'];
243 DBA::close($parents);
245 if (empty($data['to'])) {
246 $data['to'] = $data['cc'];
253 public static function fetchTargetInboxes($item, $uid)
255 $permissions = self::createPermissionBlockForItem($item);
256 if (empty($permissions)) {
262 if ($item['gravity'] == GRAVITY_ACTIVITY) {
263 $item_profile = ActivityPub::fetchprofile($item['author-link']);
265 $item_profile = ActivityPub::fetchprofile($item['owner-link']);
268 $elements = ['to', 'cc', 'bto', 'bcc'];
269 foreach ($elements as $element) {
270 if (empty($permissions[$element])) {
274 foreach ($permissions[$element] as $receiver) {
275 if ($receiver == $item_profile['followers']) {
276 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
277 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
278 while ($contact = DBA::fetch($contacts)) {
279 $contact = defaults($contact, 'batch', $contact['notify']);
280 $inboxes[$contact] = $contact;
282 DBA::close($contacts);
284 $profile = self::fetchprofile($receiver);
285 if (!empty($profile)) {
286 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
287 $inboxes[$target] = $target;
296 public static function getTypeOfItem($item)
298 if ($item['verb'] == ACTIVITY_POST) {
299 if ($item['created'] == $item['edited']) {
304 } elseif ($item['verb'] == ACTIVITY_LIKE) {
306 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
308 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
310 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
312 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
313 $type = 'TentativeAccept';
321 public static function createActivityFromItem($item_id, $object_mode = false)
323 $item = Item::selectFirst([], ['id' => $item_id]);
325 if (!DBA::isResult($item)) {
329 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
330 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
331 if (DBA::isResult($conversation)) {
332 $data = json_decode($conversation['source']);
338 $type = self::getTypeOfItem($item);
341 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
342 ['ostatus' => 'http://ostatus.org#', 'uuid' => 'http://schema.org/identifier',
343 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
344 'atomUri' => 'ostatus:atomUri', 'conversation' => 'ostatus:conversation',
345 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
347 if ($item['deleted']) {
354 $data['id'] = $item['uri'] . '#' . $type;
355 $data['type'] = $type;
356 $data['actor'] = $item['author-link'];
358 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
360 if ($item["created"] != $item["edited"]) {
361 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
364 $data['context'] = self::createConversationURLFromItem($item);
366 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
368 if (in_array($data['type'], ['Create', 'Update', 'Announce'])) {
369 $data['object'] = self::CreateNote($item);
370 } elseif ($data['type'] == 'Undo') {
371 $data['object'] = self::createActivityFromItem($item_id, true);
373 $data['object'] = $item['thr-parent'];
376 $owner = User::getOwnerDataById($item['uid']);
379 return LDSignature::sign($data, $owner);
385 public static function createObjectFromItemID($item_id)
387 $item = Item::selectFirst([], ['id' => $item_id]);
389 if (!DBA::isResult($item)) {
393 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
394 ['ostatus' => 'http://ostatus.org#', 'uuid' => 'http://schema.org/identifier',
395 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
396 'atomUri' => 'ostatus:atomUri', 'conversation' => 'ostatus:conversation',
397 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
399 $data = array_merge($data, self::CreateNote($item));
405 private static function createTagList($item)
409 $terms = Term::tagArrayFromItemId($item['id']);
410 foreach ($terms as $term) {
411 if ($term['type'] == TERM_MENTION) {
412 $contact = Contact::getDetailsByURL($term['url']);
413 if (!empty($contact['addr'])) {
414 $mention = '@' . $contact['addr'];
416 $mention = '@' . $term['url'];
419 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
425 private static function createConversationURLFromItem($item)
427 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
428 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
429 $conversation_uri = $conversation['conversation-uri'];
431 $conversation_uri = $item['parent-uri'];
433 return $conversation_uri;
436 private static function CreateNote($item)
438 if (!empty($item['title'])) {
445 $data['id'] = $item['uri'];
446 $data['type'] = $type;
447 $data['summary'] = null; // Ignore by now
449 if ($item['uri'] != $item['thr-parent']) {
450 $data['inReplyTo'] = $item['thr-parent'];
452 $data['inReplyTo'] = null;
455 $data['uuid'] = $item['guid'];
456 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
458 if ($item["created"] != $item["edited"]) {
459 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
462 $data['url'] = $item['plink'];
463 $data['attributedTo'] = $item['author-link'];
464 $data['actor'] = $item['author-link'];
465 $data['sensitive'] = false; // - Query NSFW
466 $data['conversation'] = $data['context'] = self::createConversationURLFromItem($item);
468 if (!empty($item['title'])) {
469 $data['name'] = BBCode::convert($item['title'], false, 7);
472 $data['content'] = BBCode::convert($item['body'], false, 7);
473 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
474 $data['attachment'] = []; // @ToDo
475 $data['tag'] = self::createTagList($item);
476 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
478 //$data['emoji'] = []; // Ignore by now
482 public static function transmitActivity($activity, $target, $uid)
484 $profile = self::fetchprofile($target);
486 $owner = User::getOwnerDataById($uid);
488 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
489 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
491 'actor' => $owner['url'],
492 'object' => $profile['url'],
493 'to' => $profile['url']];
495 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
497 $signed = LDSignature::sign($data, $owner);
498 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
501 public static function transmitContactAccept($target, $id, $uid)
503 $profile = self::fetchprofile($target);
505 $owner = User::getOwnerDataById($uid);
506 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
507 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
509 'actor' => $owner['url'],
510 'object' => ['id' => $id, 'type' => 'Follow',
511 'actor' => $profile['url'],
512 'object' => $owner['url']],
513 'to' => $profile['url']];
515 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
517 $signed = LDSignature::sign($data, $owner);
518 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
521 public static function transmitContactReject($target, $id, $uid)
523 $profile = self::fetchprofile($target);
525 $owner = User::getOwnerDataById($uid);
526 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
527 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
529 'actor' => $owner['url'],
530 'object' => ['id' => $id, 'type' => 'Follow',
531 'actor' => $profile['url'],
532 'object' => $owner['url']],
533 'to' => $profile['url']];
535 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
537 $signed = LDSignature::sign($data, $owner);
538 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
541 public static function transmitContactUndo($target, $uid)
543 $profile = self::fetchprofile($target);
545 $id = System::baseUrl() . '/activity/' . System::createGUID();
547 $owner = User::getOwnerDataById($uid);
548 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
551 'actor' => $owner['url'],
552 'object' => ['id' => $id, 'type' => 'Follow',
553 'actor' => $owner['url'],
554 'object' => $profile['url']],
555 'to' => $profile['url']];
557 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
559 $signed = LDSignature::sign($data, $owner);
560 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
564 * Fetches ActivityPub content from the given url
566 * @param string $url content url
569 public static function fetchContent($url)
571 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
572 if (!$ret['success'] || empty($ret['body'])) {
576 return json_decode($ret['body'], true);
580 * Resolves the profile url from the address by using webfinger
582 * @param string $addr profile address (user@domain.tld)
585 private static function addrToUrl($addr)
587 $addr_parts = explode('@', $addr);
588 if (count($addr_parts) != 2) {
592 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
594 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
595 if (!$ret['success'] || empty($ret['body'])) {
599 $data = json_decode($ret['body'], true);
601 if (empty($data['links'])) {
605 foreach ($data['links'] as $link) {
606 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
610 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
611 return $link['href'];
618 public static function fetchprofile($url, $update = false)
625 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
626 if (DBA::isResult($apcontact)) {
630 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
631 if (DBA::isResult($apcontact)) {
635 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
636 if (DBA::isResult($apcontact)) {
641 if (empty(parse_url($url, PHP_URL_SCHEME))) {
642 $url = self::addrToUrl($url);
648 $data = self::fetchContent($url);
650 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
655 $apcontact['url'] = $data['id'];
656 $apcontact['uuid'] = defaults($data, 'uuid', null);
657 $apcontact['type'] = defaults($data, 'type', null);
658 $apcontact['following'] = defaults($data, 'following', null);
659 $apcontact['followers'] = defaults($data, 'followers', null);
660 $apcontact['inbox'] = defaults($data, 'inbox', null);
661 $apcontact['outbox'] = defaults($data, 'outbox', null);
662 $apcontact['sharedinbox'] = JsonLD::fetchElement($data, 'endpoints', 'sharedInbox');
663 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
664 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
665 $apcontact['about'] = defaults($data, 'summary', '');
666 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon', 'url');
667 $apcontact['alias'] = JsonLD::fetchElement($data, 'url', 'href');
669 $parts = parse_url($apcontact['url']);
670 unset($parts['scheme']);
671 unset($parts['path']);
672 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
674 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data, 'publicKey', 'publicKeyPem'));
677 // manuallyApprovesFollowers
680 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
682 // Unhandled from Misskey
683 // sharedInbox, isCat
685 // Unhandled from Kroeg
686 // kroeg:blocks, updated
688 // Check if the address is resolvable
689 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
690 $parts = parse_url($apcontact['url']);
691 unset($parts['path']);
692 $apcontact['baseurl'] = Network::unparseURL($parts);
694 $apcontact['addr'] = null;
697 if ($apcontact['url'] == $apcontact['alias']) {
698 $apcontact['alias'] = null;
701 $apcontact['updated'] = DateTimeFormat::utcNow();
703 DBA::update('apcontact', $apcontact, ['url' => $url], true);
709 * Fetches a profile from the given url into an array that is compatible to Probe::uri
711 * @param string $url profile url
714 public static function probeProfile($url)
716 $apcontact = self::fetchprofile($url, true);
717 if (empty($apcontact)) {
721 $profile = ['network' => Protocol::ACTIVITYPUB];
722 $profile['nick'] = $apcontact['nick'];
723 $profile['name'] = $apcontact['name'];
724 $profile['guid'] = $apcontact['uuid'];
725 $profile['url'] = $apcontact['url'];
726 $profile['addr'] = $apcontact['addr'];
727 $profile['alias'] = $apcontact['alias'];
728 $profile['photo'] = $apcontact['photo'];
729 // $profile['community']
730 // $profile['keywords']
731 // $profile['location']
732 $profile['about'] = $apcontact['about'];
733 $profile['batch'] = $apcontact['sharedinbox'];
734 $profile['notify'] = $apcontact['inbox'];
735 $profile['poll'] = $apcontact['outbox'];
736 $profile['pubkey'] = $apcontact['pubkey'];
737 $profile['baseurl'] = $apcontact['baseurl'];
739 // Remove all "null" fields
740 foreach ($profile as $field => $content) {
741 if (is_null($content)) {
742 unset($profile[$field]);
749 public static function processInbox($body, $header, $uid)
751 $http_signer = HTTPSignature::getSigner($body, $header);
752 if (empty($http_signer)) {
753 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
756 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
759 $activity = json_decode($body, true);
761 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
762 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
764 if (empty($activity)) {
765 logger('Invalid body.', LOGGER_DEBUG);
769 if (LDSignature::isSigned($activity)) {
770 $ld_signer = LDSignature::getSigner($activity);
771 if (!empty($ld_signer && ($actor == $http_signer))) {
772 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
773 $trust_source = true;
774 } elseif (!empty($ld_signer)) {
775 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
776 $trust_source = true;
777 } elseif ($actor == $http_signer) {
778 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
779 $trust_source = true;
781 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
782 $trust_source = false;
784 } elseif ($actor == $http_signer) {
785 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
786 $trust_source = true;
788 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
789 $trust_source = false;
792 self::processActivity($activity, $body, $uid, $trust_source);
795 public static function fetchOutbox($url, $uid)
797 $data = self::fetchContent($url);
802 if (!empty($data['orderedItems'])) {
803 $items = $data['orderedItems'];
804 } elseif (!empty($data['first']['orderedItems'])) {
805 $items = $data['first']['orderedItems'];
806 } elseif (!empty($data['first'])) {
807 self::fetchOutbox($data['first'], $uid);
813 foreach ($items as $activity) {
814 self::processActivity($activity, '', $uid, true);
818 private static function prepareObjectData($activity, $uid, $trust_source)
820 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
822 logger('Empty actor', LOGGER_DEBUG);
826 // Fetch all receivers from to, cc, bto and bcc
827 $receivers = self::getReceivers($activity, $actor);
829 // When it is a delivery to a personal inbox we add that user to the receivers
831 $owner = User::getOwnerDataById($uid);
832 $additional = ['uid:' . $uid => $uid];
833 $receivers = array_merge($receivers, $additional);
836 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
838 if (is_string($activity['object'])) {
839 $object_url = $activity['object'];
840 } elseif (!empty($activity['object']['id'])) {
841 $object_url = $activity['object']['id'];
843 logger('No object found', LOGGER_DEBUG);
847 // Fetch the content only on activities where this matters
848 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
849 $object_data = self::fetchObject($object_url, $activity['object'], $trust_source);
850 if (empty($object_data)) {
851 logger("Object data couldn't be processed", LOGGER_DEBUG);
854 } elseif ($activity['type'] == 'Accept') {
856 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
857 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'actor');
858 } elseif ($activity['type'] == 'Undo') {
860 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
861 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'object');
862 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
863 // Create a mostly empty array out of the activity data (instead of the object).
864 // This way we later don't have to check for the existence of ech individual array element.
865 $object_data = self::processCommonData($activity);
866 $object_data['name'] = $activity['type'];
867 $object_data['author'] = $activity['actor'];
868 $object_data['object'] = $object_url;
869 } elseif ($activity['type'] == 'Follow') {
870 $object_data['id'] = $activity['id'];
871 $object_data['object'] = $object_url;
876 $object_data = self::addActivityFields($object_data, $activity);
878 $object_data['type'] = $activity['type'];
879 $object_data['owner'] = $actor;
880 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
885 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
887 if (empty($activity['type'])) {
888 logger('Empty type', LOGGER_DEBUG);
892 if (empty($activity['object'])) {
893 logger('Empty object', LOGGER_DEBUG);
897 if (empty($activity['actor'])) {
898 logger('Empty actor', LOGGER_DEBUG);
904 // title, atomUri, context_id, statusnetConversationId
907 // context, location, signature;
909 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
911 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
912 if (empty($object_data)) {
913 logger('No object data found', LOGGER_DEBUG);
917 switch ($activity['type']) {
920 self::createItem($object_data, $body);
924 self::likeItem($object_data, $body);
928 self::dislikeItem($object_data, $body);
938 self::followUser($object_data);
942 if ($object_data['object_type'] == 'Follow') {
943 self::acceptFollowUser($object_data);
948 if ($object_data['object_type'] == 'Follow') {
949 self::undoFollowUser($object_data);
954 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
959 private static function getReceivers($activity, $actor)
963 // When it is an answer, we inherite the receivers from the parent
964 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
965 if (!empty($replyto)) {
966 $parents = Item::select(['uid'], ['uri' => $replyto]);
967 while ($parent = Item::fetch($parents)) {
968 $receivers['uid:' . $parent['uid']] = $parent['uid'];
972 if (!empty($actor)) {
973 $profile = self::fetchprofile($actor);
974 $followers = defaults($profile, 'followers', '');
976 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
978 logger('Empty actor', LOGGER_DEBUG);
982 $elements = ['to', 'cc', 'bto', 'bcc'];
983 foreach ($elements as $element) {
984 if (empty($activity[$element])) {
988 // The receiver can be an arror or a string
989 if (is_string($activity[$element])) {
990 $activity[$element] = [$activity[$element]];
993 foreach ($activity[$element] as $receiver) {
994 if ($receiver == self::PUBLIC) {
995 $receivers['uid:0'] = 0;
998 if (($receiver == self::PUBLIC) && !empty($actor)) {
999 // This will most likely catch all OStatus connections to Mastodon
1000 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1001 $contacts = DBA::select('contact', ['uid'], $condition);
1002 while ($contact = DBA::fetch($contacts)) {
1003 if ($contact['uid'] != 0) {
1004 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1007 DBA::close($contacts);
1010 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1011 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1012 'network' => Protocol::ACTIVITYPUB];
1013 $contacts = DBA::select('contact', ['uid'], $condition);
1014 while ($contact = DBA::fetch($contacts)) {
1015 if ($contact['uid'] != 0) {
1016 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1019 DBA::close($contacts);
1023 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1024 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1025 if (!DBA::isResult($contact)) {
1028 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1034 private static function addActivityFields($object_data, $activity)
1036 if (!empty($activity['published']) && empty($object_data['published'])) {
1037 $object_data['published'] = $activity['published'];
1040 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1041 $object_data['updated'] = $activity['updated'];
1044 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1045 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1048 if (!empty($activity['instrument'])) {
1049 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1051 return $object_data;
1054 private static function fetchObject($object_url, $object = [], $trust_source = false)
1056 if (!$trust_source || is_string($object)) {
1057 $data = self::fetchContent($object_url);
1059 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1060 $data = $object_url;
1062 logger('Fetched content for ' . $object_url, LOGGER_DEBUG);
1065 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1069 if (is_string($data)) {
1070 $item = Item::selectFirst([], ['uri' => $data]);
1071 if (!DBA::isResult($item)) {
1072 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1075 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1076 $data = self::CreateNote($item);
1079 if (empty($data['type'])) {
1080 logger('Empty type', LOGGER_DEBUG);
1083 $type = $data['type'];
1084 logger('Type ' . $type, LOGGER_DEBUG);
1087 if (in_array($type, ['Note', 'Article', 'Video'])) {
1088 $common = self::processCommonData($data);
1093 return array_merge($common, self::processNote($data));
1095 return array_merge($common, self::processArticle($data));
1097 return array_merge($common, self::processVideo($data));
1100 if (empty($data['object'])) {
1103 return self::fetchObject($data['object']);
1110 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1115 private static function processCommonData(&$object)
1117 if (empty($object['id'])) {
1122 $object_data['type'] = $object['type'];
1123 $object_data['uri'] = $object['id'];
1125 if (!empty($object['inReplyTo'])) {
1126 $object_data['reply-to-uri'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1128 $object_data['reply-to-uri'] = $object_data['uri'];
1131 $object_data['published'] = defaults($object, 'published', null);
1132 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1134 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1135 $object_data['published'] = $object_data['updated'];
1138 $object_data['uuid'] = defaults($object, 'uuid', null);
1139 $object_data['owner'] = $object_data['author'] = JsonLD::fetchElement($object, 'attributedTo', 'id');
1140 $object_data['context'] = defaults($object, 'context', null);
1141 $object_data['conversation'] = defaults($object, 'conversation', null);
1142 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1143 $object_data['name'] = defaults($object, 'title', null);
1144 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1145 $object_data['summary'] = defaults($object, 'summary', null);
1146 $object_data['content'] = defaults($object, 'content', null);
1147 $object_data['source'] = defaults($object, 'source', null);
1148 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1149 $object_data['attachments'] = defaults($object, 'attachment', null);
1150 $object_data['tags'] = defaults($object, 'tag', null);
1151 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1152 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1153 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1156 // @context, type, actor, signature, mediaType, duration, replies, icon
1158 // Also missing: (Defined in the standard, but currently unused)
1159 // audience, preview, endTime, startTime, generator, image
1161 return $object_data;
1164 private static function processNote($object)
1169 // emoji, atomUri, inReplyToAtomUri
1172 // contentMap, announcement_count, announcements, context_id, likes, like_count
1173 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1175 return $object_data;
1178 private static function processArticle($object)
1182 return $object_data;
1185 private static function processVideo($object)
1190 // category, licence, language, commentsEnabled
1193 // views, waitTranscoding, state, support, subtitleLanguage
1194 // likes, dislikes, shares, comments
1196 return $object_data;
1199 private static function convertMentions($body)
1201 $URLSearchString = "^\[\]";
1202 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1207 private static function constructTagList($tags, $sensitive)
1214 foreach ($tags as $tag) {
1215 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1216 if (!empty($tag_text)) {
1220 if (empty($tag['href'])) {
1225 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1229 /// @todo add nsfw for $sensitive
1234 private static function constructAttachList($attachments, $item)
1236 if (empty($attachments)) {
1240 foreach ($attachments as $attach) {
1241 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1242 if ($filetype == 'image') {
1243 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1245 if (!empty($item["attach"])) {
1246 $item["attach"] .= ',';
1248 $item["attach"] = '';
1250 if (!isset($attach['length'])) {
1251 $attach['length'] = "0";
1253 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1260 private static function createItem($activity, $body)
1263 $item['verb'] = ACTIVITY_POST;
1264 $item['parent-uri'] = $activity['reply-to-uri'];
1266 if ($activity['reply-to-uri'] == $activity['uri']) {
1267 $item['gravity'] = GRAVITY_PARENT;
1268 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1270 $item['gravity'] = GRAVITY_COMMENT;
1271 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1274 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1275 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1276 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1279 self::postItem($activity, $item, $body);
1282 private static function likeItem($activity, $body)
1285 $item['verb'] = ACTIVITY_LIKE;
1286 $item['parent-uri'] = $activity['object'];
1287 $item['gravity'] = GRAVITY_ACTIVITY;
1288 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1290 self::postItem($activity, $item, $body);
1293 private static function dislikeItem($activity, $body)
1296 $item['verb'] = ACTIVITY_DISLIKE;
1297 $item['parent-uri'] = $activity['object'];
1298 $item['gravity'] = GRAVITY_ACTIVITY;
1299 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1301 self::postItem($activity, $item, $body);
1304 private static function postItem($activity, $item, $body)
1306 /// @todo What to do with $activity['context']?
1308 $item['network'] = Protocol::ACTIVITYPUB;
1309 $item['private'] = !in_array(0, $activity['receiver']);
1310 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1311 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1312 $item['uri'] = $activity['uri'];
1313 $item['created'] = $activity['published'];
1314 $item['edited'] = $activity['updated'];
1315 $item['guid'] = $activity['uuid'];
1316 $item['title'] = HTML::toBBCode($activity['name']);
1317 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1318 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1319 $item['location'] = $activity['location'];
1320 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1321 $item['app'] = $activity['service'];
1322 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1324 $item = self::constructAttachList($activity['attachments'], $item);
1326 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1327 if (!empty($source)) {
1328 $item['body'] = $source;
1331 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1332 $item['source'] = $body;
1333 $item['conversation-uri'] = $activity['conversation'];
1335 foreach ($activity['receiver'] as $receiver) {
1336 $item['uid'] = $receiver;
1337 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1339 if (($receiver != 0) && empty($item['contact-id'])) {
1340 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1343 $item_id = Item::insert($item);
1344 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1348 private static function fetchMissingActivity($url, $child)
1350 $object = ActivityPub::fetchContent($url);
1351 if (empty($object)) {
1352 logger('Activity ' . $url . ' was not fetchable, aborting.');
1357 $activity['@context'] = $object['@context'];
1358 unset($object['@context']);
1359 $activity['id'] = $object['id'];
1360 $activity['to'] = defaults($object, 'to', []);
1361 $activity['cc'] = defaults($object, 'cc', []);
1362 $activity['actor'] = $child['author'];
1363 $activity['object'] = $object;
1364 $activity['published'] = $object['published'];
1365 $activity['type'] = 'Create';
1367 self::processActivity($activity);
1368 logger('Activity ' . $url . ' had been fetched and processed.');
1371 private static function getUserOfObject($object)
1373 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1374 if (!DBA::isResult($self)) {
1377 return $self['uid'];
1381 private static function followUser($activity)
1383 $uid = self::getUserOfObject($activity['object']);
1388 $owner = User::getOwnerDataById($uid);
1390 $cid = Contact::getIdForURL($activity['owner'], $uid);
1392 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1397 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1398 'author-link' => $activity['owner']];
1400 Contact::addRelationship($owner, $contact, $item);
1401 $cid = Contact::getIdForURL($activity['owner'], $uid);
1406 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1407 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1408 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1411 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1412 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1415 private static function acceptFollowUser($activity)
1417 $uid = self::getUserOfObject($activity['object']);
1422 $owner = User::getOwnerDataById($uid);
1424 $cid = Contact::getIdForURL($activity['owner'], $uid);
1426 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1430 $fields = ['pending' => false];
1432 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1433 if ($contact['rel'] == Contact::FOLLOWER) {
1434 $fields['rel'] = Contact::FRIEND;
1437 $condition = ['id' => $cid];
1438 DBA::update('contact', $fields, $condition);
1439 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1442 private static function undoFollowUser($activity)
1444 $uid = self::getUserOfObject($activity['object']);
1449 $owner = User::getOwnerDataById($uid);
1451 $cid = Contact::getIdForURL($activity['owner'], $uid);
1453 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1457 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1458 if (!DBA::isResult($contact)) {
1462 Contact::removeFollower($owner, $contact);
1463 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);