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\Profile;
17 use Friendica\Model\Term;
18 use Friendica\Model\User;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\Crypto;
21 use Friendica\Content\Text\BBCode;
22 use Friendica\Content\Text\HTML;
23 use Friendica\Util\JsonLD;
24 use Friendica\Util\LDSignature;
25 use Friendica\Core\Config;
28 * @brief ActivityPub Protocol class
29 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
30 * https://www.w3.org/TR/activitypub/
31 * https://www.w3.org/TR/activitystreams-core/
32 * https://www.w3.org/TR/activitystreams-vocabulary/
34 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
35 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
37 * Digest: https://tools.ietf.org/html/rfc5843
38 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
40 * Mastodon implementation of supported activities:
41 * https://github.com/tootsuite/mastodon/blob/master/app/lib/activitypub/activity.rb#L26
71 * - Queueing unsucessful deliveries
72 * - Polling the outboxes for missing content?
73 * - Possibly using the LD-JSON parser
77 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
78 const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
79 ['ostatus' => 'http://ostatus.org#', 'uuid' => 'http://schema.org/identifier',
80 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
81 'atomUri' => 'ostatus:atomUri', 'conversation' => 'ostatus:conversation',
82 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']];
84 public static function isRequest()
86 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
87 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
90 public static function getFollowers($owner, $page = null)
92 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
93 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
94 $count = DBA::count('contact', $condition);
96 $data = ['@context' => self::CONTEXT];
97 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
98 $data['type'] = 'OrderedCollection';
99 $data['totalItems'] = $count;
101 // When we hide our friends we will only show the pure number but don't allow more.
102 $profile = Profile::getProfileForUser($owner['uid']);
103 if (!empty($profile['hide-friends'])) {
108 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
112 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
113 while ($contact = DBA::fetch($contacts)) {
114 $list[] = $contact['url'];
118 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
121 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
123 $data['orderedItems'] = $list;
129 public static function getFollowing($owner, $page = null)
131 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
132 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
133 $count = DBA::count('contact', $condition);
135 $data = ['@context' => self::CONTEXT];
136 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
137 $data['type'] = 'OrderedCollection';
138 $data['totalItems'] = $count;
140 // When we hide our friends we will only show the pure number but don't allow more.
141 $profile = Profile::getProfileForUser($owner['uid']);
142 if (!empty($profile['hide-friends'])) {
147 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
151 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
152 while ($contact = DBA::fetch($contacts)) {
153 $list[] = $contact['url'];
157 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
160 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
162 $data['orderedItems'] = $list;
168 public static function getOutbox($owner, $page = null)
170 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
172 $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
173 'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
174 'deleted' => false, 'visible' => true];
175 $count = DBA::count('item', $condition);
177 $data = ['@context' => self::CONTEXT];
178 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
179 $data['type'] = 'OrderedCollection';
180 $data['totalItems'] = $count;
183 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
187 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
189 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
190 while ($item = Item::fetch($items)) {
191 $object = self::createObjectFromItemID($item['id']);
192 unset($object['@context']);
197 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
200 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
202 $data['orderedItems'] = $list;
209 * Return the ActivityPub profile of the given user
211 * @param integer $uid User ID
214 public static function profile($uid)
216 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
217 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
218 'account_removed' => false, 'verified' => true];
219 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
220 $user = DBA::selectFirst('user', $fields, $condition);
221 if (!DBA::isResult($user)) {
225 $fields = ['locality', 'region', 'country-name'];
226 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
227 if (!DBA::isResult($profile)) {
231 $fields = ['name', 'url', 'location', 'about', 'avatar'];
232 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
233 if (!DBA::isResult($contact)) {
237 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
238 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
239 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
241 $data['id'] = $contact['url'];
242 $data['uuid'] = $user['guid'];
243 $data['type'] = $accounttype[$user['account-type']];
244 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
245 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
246 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
247 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
248 $data['preferredUsername'] = $user['nickname'];
249 $data['name'] = $contact['name'];
250 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
251 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
252 $data['summary'] = $contact['about'];
253 $data['url'] = $contact['url'];
254 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
255 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
256 'owner' => $contact['url'],
257 'publicKeyPem' => $user['pubkey']];
258 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
259 $data['icon'] = ['type' => 'Image',
260 'url' => $contact['avatar']];
262 // tags: https://kitty.town/@inmysocks/100656097926961126.json
266 private static function fetchPermissionBlockFromConversation($item)
268 if (empty($item['thr-parent'])) {
272 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
273 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
274 if (!DBA::isResult($conversation)) {
278 $activity = json_decode($conversation['source'], true);
280 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
281 $profile = ActivityPub::fetchprofile($actor);
283 $item_profile = ActivityPub::fetchprofile($item['author-link']);
284 $exclude[] = $item['author-link'];
286 if ($item['gravity'] == GRAVITY_PARENT) {
287 $exclude[] = $item['owner-link'];
290 $permissions['to'][] = $actor;
292 $elements = ['to', 'cc', 'bto', 'bcc'];
293 foreach ($elements as $element) {
294 if (empty($activity[$element])) {
297 if (is_string($activity[$element])) {
298 $activity[$element] = [$activity[$element]];
301 foreach ($activity[$element] as $receiver) {
302 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
303 $receiver = $item_profile['followers'];
305 if (!in_array($receiver, $exclude)) {
306 $permissions[$element][] = $receiver;
313 public static function createPermissionBlockForItem($item)
315 $data = ['to' => [], 'cc' => []];
317 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
319 $actor_profile = ActivityPub::fetchprofile($item['author-link']);
321 $terms = Term::tagArrayFromItemId($item['id']);
323 $contacts[$item['author-link']] = $item['author-link'];
325 if (!$item['private']) {
326 $data['to'][] = self::PUBLIC;
327 if (!empty($actor_profile['followers'])) {
328 $data['cc'][] = $actor_profile['followers'];
331 foreach ($terms as $term) {
332 if ($term['type'] != TERM_MENTION) {
335 $profile = self::fetchprofile($term['url'], false);
336 if (!empty($profile) && empty($contacts[$profile['url']])) {
337 $data['cc'][] = $profile['url'];
338 $contacts[$profile['url']] = $profile['url'];
342 $receiver_list = Item::enumeratePermissions($item);
346 foreach ($terms as $term) {
347 if ($term['type'] != TERM_MENTION) {
350 $cid = Contact::getIdForURL($term['url'], $item['uid']);
351 if (!empty($cid) && in_array($cid, $receiver_list)) {
352 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
353 $data['to'][] = $contact['url'];
354 $contacts[$contact['url']] = $contact['url'];
358 foreach ($receiver_list as $receiver) {
359 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
360 if (empty($contacts[$contact['url']])) {
361 $data['cc'][] = $contact['url'];
362 $contacts[$contact['url']] = $contact['url'];
367 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
368 while ($parent = Item::fetch($parents)) {
369 // Don't include data from future posts
370 if ($parent['id'] >= $item['id']) {
374 $profile = self::fetchprofile($parent['author-link'], false);
375 if (!empty($profile) && empty($contacts[$profile['url']])) {
376 $data['cc'][] = $profile['url'];
377 $contacts[$profile['url']] = $profile['url'];
380 if ($item['gravity'] != GRAVITY_PARENT) {
384 $profile = self::fetchprofile($parent['owner-link'], false);
385 if (!empty($profile) && empty($contacts[$profile['url']])) {
386 $data['cc'][] = $profile['url'];
387 $contacts[$profile['url']] = $profile['url'];
390 DBA::close($parents);
392 if (empty($data['to'])) {
393 $data['to'] = $data['cc'];
400 public static function fetchTargetInboxes($item, $uid)
402 $permissions = self::createPermissionBlockForItem($item);
403 if (empty($permissions)) {
409 if ($item['gravity'] == GRAVITY_ACTIVITY) {
410 $item_profile = ActivityPub::fetchprofile($item['author-link']);
412 $item_profile = ActivityPub::fetchprofile($item['owner-link']);
415 $elements = ['to', 'cc', 'bto', 'bcc'];
416 foreach ($elements as $element) {
417 if (empty($permissions[$element])) {
421 foreach ($permissions[$element] as $receiver) {
422 if ($receiver == $item_profile['followers']) {
423 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
424 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
425 while ($contact = DBA::fetch($contacts)) {
426 $contact = defaults($contact, 'batch', $contact['notify']);
427 $inboxes[$contact] = $contact;
429 DBA::close($contacts);
431 $profile = self::fetchprofile($receiver);
432 if (!empty($profile)) {
433 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
434 $inboxes[$target] = $target;
443 public static function getTypeOfItem($item)
445 if ($item['verb'] == ACTIVITY_POST) {
446 if ($item['created'] == $item['edited']) {
451 } elseif ($item['verb'] == ACTIVITY_LIKE) {
453 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
455 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
457 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
459 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
460 $type = 'TentativeAccept';
468 public static function createActivityFromItem($item_id, $object_mode = false)
470 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
472 if (!DBA::isResult($item)) {
476 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
477 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
478 if (DBA::isResult($conversation)) {
479 $data = json_decode($conversation['source']);
485 $type = self::getTypeOfItem($item);
488 $data = ['@context' => self::CONTEXT];
490 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
492 } elseif ($item['deleted']) {
499 $data['id'] = $item['uri'] . '#' . $type;
500 $data['type'] = $type;
501 $data['actor'] = $item['author-link'];
503 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
505 if ($item["created"] != $item["edited"]) {
506 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
509 $data['context'] = self::fetchContextURLForItem($item);
511 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
513 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
514 $data['object'] = self::CreateNote($item);
515 } elseif ($data['type'] == 'Undo') {
516 $data['object'] = self::createActivityFromItem($item_id, true);
518 $data['object'] = $item['thr-parent'];
521 $owner = User::getOwnerDataById($item['uid']);
524 return LDSignature::sign($data, $owner);
530 public static function createObjectFromItemID($item_id)
532 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
534 if (!DBA::isResult($item)) {
538 $data = ['@context' => self::CONTEXT];
539 $data = array_merge($data, self::CreateNote($item));
544 private static function createTagList($item)
548 $terms = Term::tagArrayFromItemId($item['id']);
549 foreach ($terms as $term) {
550 if ($term['type'] == TERM_MENTION) {
551 $contact = Contact::getDetailsByURL($term['url']);
552 if (!empty($contact['addr'])) {
553 $mention = '@' . $contact['addr'];
555 $mention = '@' . $term['url'];
558 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
564 private static function fetchConversationURLForItem($item)
566 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
567 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
568 $conversation_uri = $conversation['conversation-uri'];
569 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
570 $conversation_uri = $conversation['conversation-href'];
572 $conversation_uri = str_replace('/object/', '/context/', $item['parent-uri']);
574 return $conversation_uri;
577 private static function fetchContextURLForItem($item)
579 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
580 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
581 $context_uri = $conversation['conversation-href'];
582 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
583 $context_uri = $conversation['conversation-uri'];
585 $context_uri = str_replace('/object/', '/context/', $item['parent-uri']);
590 private static function CreateNote($item)
592 if (!empty($item['title'])) {
598 if ($item['deleted']) {
603 $data['id'] = $item['uri'];
604 $data['type'] = $type;
606 if ($item['deleted']) {
610 $data['summary'] = null; // Ignore by now
612 if ($item['uri'] != $item['thr-parent']) {
613 $data['inReplyTo'] = $item['thr-parent'];
615 $data['inReplyTo'] = null;
618 $data['uuid'] = $item['guid'];
619 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
621 if ($item["created"] != $item["edited"]) {
622 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
625 $data['url'] = $item['plink'];
626 $data['attributedTo'] = $item['author-link'];
627 $data['actor'] = $item['author-link'];
628 $data['sensitive'] = false; // - Query NSFW
629 $data['conversation'] = self::fetchConversationURLForItem($item);
630 $data['context'] = self::fetchContextURLForItem($item);
632 if (!empty($item['title'])) {
633 $data['name'] = BBCode::convert($item['title'], false, 7);
636 $data['content'] = BBCode::convert($item['body'], false, 7);
637 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
638 $data['attachment'] = []; // @ToDo
639 $data['tag'] = self::createTagList($item);
640 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
645 public static function transmitActivity($activity, $target, $uid)
647 $profile = self::fetchprofile($target);
649 $owner = User::getOwnerDataById($uid);
651 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
652 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
654 'actor' => $owner['url'],
655 'object' => $profile['url'],
656 'to' => $profile['url']];
658 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
660 $signed = LDSignature::sign($data, $owner);
661 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
664 public static function transmitContactAccept($target, $id, $uid)
666 $profile = self::fetchprofile($target);
668 $owner = User::getOwnerDataById($uid);
669 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
670 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
672 'actor' => $owner['url'],
673 'object' => ['id' => $id, 'type' => 'Follow',
674 'actor' => $profile['url'],
675 'object' => $owner['url']],
676 'to' => $profile['url']];
678 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
680 $signed = LDSignature::sign($data, $owner);
681 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
684 public static function transmitContactReject($target, $id, $uid)
686 $profile = self::fetchprofile($target);
688 $owner = User::getOwnerDataById($uid);
689 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
690 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
692 'actor' => $owner['url'],
693 'object' => ['id' => $id, 'type' => 'Follow',
694 'actor' => $profile['url'],
695 'object' => $owner['url']],
696 'to' => $profile['url']];
698 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
700 $signed = LDSignature::sign($data, $owner);
701 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
704 public static function transmitContactUndo($target, $uid)
706 $profile = self::fetchprofile($target);
708 $id = System::baseUrl() . '/activity/' . System::createGUID();
710 $owner = User::getOwnerDataById($uid);
711 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
714 'actor' => $owner['url'],
715 'object' => ['id' => $id, 'type' => 'Follow',
716 'actor' => $owner['url'],
717 'object' => $profile['url']],
718 'to' => $profile['url']];
720 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
722 $signed = LDSignature::sign($data, $owner);
723 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
727 * Fetches ActivityPub content from the given url
729 * @param string $url content url
732 public static function fetchContent($url)
734 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
735 if (!$ret['success'] || empty($ret['body'])) {
738 return json_decode($ret['body'], true);
742 * Resolves the profile url from the address by using webfinger
744 * @param string $addr profile address (user@domain.tld)
747 private static function addrToUrl($addr)
749 $addr_parts = explode('@', $addr);
750 if (count($addr_parts) != 2) {
754 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
756 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
757 if (!$ret['success'] || empty($ret['body'])) {
761 $data = json_decode($ret['body'], true);
763 if (empty($data['links'])) {
767 foreach ($data['links'] as $link) {
768 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
772 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
773 return $link['href'];
781 * Fetches a profile form a given url
783 * @param string $url profile url
784 * @param boolean $update true = always update, false = never update, null = update when not found
785 * @return array profile array
787 public static function fetchprofile($url, $update = null)
793 if (empty($update)) {
794 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
795 if (DBA::isResult($apcontact)) {
799 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
800 if (DBA::isResult($apcontact)) {
804 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
805 if (DBA::isResult($apcontact)) {
809 if (!is_null($update)) {
814 if (empty(parse_url($url, PHP_URL_SCHEME))) {
815 $url = self::addrToUrl($url);
821 $data = self::fetchContent($url);
823 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
828 $apcontact['url'] = $data['id'];
829 $apcontact['uuid'] = defaults($data, 'uuid', null);
830 $apcontact['type'] = defaults($data, 'type', null);
831 $apcontact['following'] = defaults($data, 'following', null);
832 $apcontact['followers'] = defaults($data, 'followers', null);
833 $apcontact['inbox'] = defaults($data, 'inbox', null);
834 $apcontact['outbox'] = defaults($data, 'outbox', null);
835 $apcontact['sharedinbox'] = JsonLD::fetchElement($data, 'endpoints', 'sharedInbox');
836 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
837 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
838 $apcontact['about'] = defaults($data, 'summary', '');
839 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon', 'url');
840 $apcontact['alias'] = JsonLD::fetchElement($data, 'url', 'href');
842 $parts = parse_url($apcontact['url']);
843 unset($parts['scheme']);
844 unset($parts['path']);
845 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
847 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data, 'publicKey', 'publicKeyPem'));
850 // manuallyApprovesFollowers
853 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
855 // Unhandled from Misskey
856 // sharedInbox, isCat
858 // Unhandled from Kroeg
859 // kroeg:blocks, updated
861 // Check if the address is resolvable
862 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
863 $parts = parse_url($apcontact['url']);
864 unset($parts['path']);
865 $apcontact['baseurl'] = Network::unparseURL($parts);
867 $apcontact['addr'] = null;
868 $apcontact['baseurl'] = null;
871 if ($apcontact['url'] == $apcontact['alias']) {
872 $apcontact['alias'] = null;
875 $apcontact['updated'] = DateTimeFormat::utcNow();
877 DBA::update('apcontact', $apcontact, ['url' => $url], true);
879 // Update some data in the contact table with various ways to catch them all
880 $contact_fields = ['name' => $apcontact['name'], 'about' => $apcontact['about']];
881 DBA::update('contact', $contact_fields, ['nurl' => normalise_link($url)]);
883 $contacts = DBA::select('contact', ['uid', 'id'], ['nurl' => normalise_link($url)]);
884 while ($contact = DBA::fetch($contacts)) {
885 Contact::updateAvatar($apcontact['photo'], $contact['uid'], $contact['id']);
887 DBA::close($contacts);
889 // Update the gcontact table
890 DBA::update('gcontact', $contact_fields, ['nurl' => normalise_link($url)]);
892 logger('Updated profile for ' . $url, LOGGER_DEBUG);
898 * Fetches a profile from the given url into an array that is compatible to Probe::uri
900 * @param string $url profile url
903 public static function probeProfile($url)
905 $apcontact = self::fetchprofile($url, true);
906 if (empty($apcontact)) {
910 $profile = ['network' => Protocol::ACTIVITYPUB];
911 $profile['nick'] = $apcontact['nick'];
912 $profile['name'] = $apcontact['name'];
913 $profile['guid'] = $apcontact['uuid'];
914 $profile['url'] = $apcontact['url'];
915 $profile['addr'] = $apcontact['addr'];
916 $profile['alias'] = $apcontact['alias'];
917 $profile['photo'] = $apcontact['photo'];
918 // $profile['community']
919 // $profile['keywords']
920 // $profile['location']
921 $profile['about'] = $apcontact['about'];
922 $profile['batch'] = $apcontact['sharedinbox'];
923 $profile['notify'] = $apcontact['inbox'];
924 $profile['poll'] = $apcontact['outbox'];
925 $profile['pubkey'] = $apcontact['pubkey'];
926 $profile['baseurl'] = $apcontact['baseurl'];
928 // Remove all "null" fields
929 foreach ($profile as $field => $content) {
930 if (is_null($content)) {
931 unset($profile[$field]);
938 public static function processInbox($body, $header, $uid)
940 $http_signer = HTTPSignature::getSigner($body, $header);
941 if (empty($http_signer)) {
942 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
945 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
948 $activity = json_decode($body, true);
950 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
951 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
953 if (empty($activity)) {
954 logger('Invalid body.', LOGGER_DEBUG);
958 if (LDSignature::isSigned($activity)) {
959 $ld_signer = LDSignature::getSigner($activity);
960 if (empty($ld_signer)) {
961 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
963 if (!empty($ld_signer && ($actor == $http_signer))) {
964 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
965 $trust_source = true;
966 } elseif (!empty($ld_signer)) {
967 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
968 $trust_source = true;
969 } elseif ($actor == $http_signer) {
970 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
971 $trust_source = true;
973 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
974 $trust_source = false;
976 } elseif ($actor == $http_signer) {
977 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
978 $trust_source = true;
980 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
981 $trust_source = false;
984 self::processActivity($activity, $body, $uid, $trust_source);
987 public static function fetchOutbox($url, $uid)
989 $data = self::fetchContent($url);
994 if (!empty($data['orderedItems'])) {
995 $items = $data['orderedItems'];
996 } elseif (!empty($data['first']['orderedItems'])) {
997 $items = $data['first']['orderedItems'];
998 } elseif (!empty($data['first'])) {
999 self::fetchOutbox($data['first'], $uid);
1005 foreach ($items as $activity) {
1006 self::processActivity($activity, '', $uid, true);
1010 private static function prepareObjectData($activity, $uid, &$trust_source)
1012 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
1013 if (empty($actor)) {
1014 logger('Empty actor', LOGGER_DEBUG);
1018 // Fetch all receivers from to, cc, bto and bcc
1019 $receivers = self::getReceivers($activity, $actor);
1021 // When it is a delivery to a personal inbox we add that user to the receivers
1023 $owner = User::getOwnerDataById($uid);
1024 $additional = ['uid:' . $uid => $uid];
1025 $receivers = array_merge($receivers, $additional);
1028 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
1030 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
1031 if (empty($object_id)) {
1032 logger('No object found', LOGGER_DEBUG);
1036 // Fetch the content only on activities where this matters
1037 if (in_array($activity['type'], ['Create', 'Announce'])) {
1038 $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
1039 if (empty($object_data)) {
1040 logger("Object data couldn't be processed", LOGGER_DEBUG);
1043 // We had been able to retrieve the object data - so we can trust the source
1044 $trust_source = true;
1045 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
1046 // Create a mostly empty array out of the activity data (instead of the object).
1047 // This way we later don't have to check for the existence of ech individual array element.
1048 $object_data = self::ProcessObject($activity);
1049 $object_data['name'] = $activity['type'];
1050 $object_data['author'] = $activity['actor'];
1051 $object_data['object'] = $object_id;
1052 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
1055 $object_data['id'] = $activity['id'];
1056 $object_data['object'] = $activity['object'];
1057 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1060 $object_data = self::addActivityFields($object_data, $activity);
1062 $object_data['type'] = $activity['type'];
1063 $object_data['owner'] = $actor;
1064 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
1066 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
1068 return $object_data;
1071 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
1073 if (empty($activity['type'])) {
1074 logger('Empty type', LOGGER_DEBUG);
1078 if (empty($activity['object'])) {
1079 logger('Empty object', LOGGER_DEBUG);
1083 if (empty($activity['actor'])) {
1084 logger('Empty actor', LOGGER_DEBUG);
1089 // $trust_source is called by reference and is set to true if the content was retrieved successfully
1090 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
1091 if (empty($object_data)) {
1092 logger('No object data found', LOGGER_DEBUG);
1096 if (!$trust_source) {
1097 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
1100 switch ($activity['type']) {
1103 self::createItem($object_data, $body);
1107 self::likeItem($object_data, $body);
1111 self::dislikeItem($object_data, $body);
1115 if (in_array($object_data['object_type'], ['Person', 'Organization', 'Service', 'Group', 'Application'])) {
1116 self::updatePerson($object_data, $body);
1124 self::followUser($object_data);
1128 if ($object_data['object_type'] == 'Follow') {
1129 self::acceptFollowUser($object_data);
1134 if ($object_data['object_type'] == 'Follow') {
1135 self::undoFollowUser($object_data);
1136 } elseif (in_array($object_data['object_type'], ['Like', 'Dislike', 'Accept', 'Reject', 'TentativeAccept'])) {
1137 self::undoActivity($object_data);
1142 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
1147 private static function getReceivers($activity, $actor)
1151 // When it is an answer, we inherite the receivers from the parent
1152 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1153 if (!empty($replyto)) {
1154 $parents = Item::select(['uid'], ['uri' => $replyto]);
1155 while ($parent = Item::fetch($parents)) {
1156 $receivers['uid:' . $parent['uid']] = $parent['uid'];
1160 if (!empty($actor)) {
1161 $profile = self::fetchprofile($actor);
1162 $followers = defaults($profile, 'followers', '');
1164 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
1166 logger('Empty actor', LOGGER_DEBUG);
1170 $elements = ['to', 'cc', 'bto', 'bcc'];
1171 foreach ($elements as $element) {
1172 if (empty($activity[$element])) {
1176 // The receiver can be an arror or a string
1177 if (is_string($activity[$element])) {
1178 $activity[$element] = [$activity[$element]];
1181 foreach ($activity[$element] as $receiver) {
1182 if ($receiver == self::PUBLIC) {
1183 $receivers['uid:0'] = 0;
1186 if (($receiver == self::PUBLIC) && !empty($actor)) {
1187 // This will most likely catch all OStatus connections to Mastodon
1188 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1189 $contacts = DBA::select('contact', ['uid'], $condition);
1190 while ($contact = DBA::fetch($contacts)) {
1191 if ($contact['uid'] != 0) {
1192 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1195 DBA::close($contacts);
1198 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1199 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1200 'network' => Protocol::ACTIVITYPUB];
1201 $contacts = DBA::select('contact', ['uid'], $condition);
1202 while ($contact = DBA::fetch($contacts)) {
1203 if ($contact['uid'] != 0) {
1204 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1207 DBA::close($contacts);
1211 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1212 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1213 if (!DBA::isResult($contact)) {
1216 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1220 self::switchContacts($receivers, $actor);
1225 private static function switchContact($cid, $uid, $url)
1227 $profile = ActivityPub::probeProfile($url);
1228 if (empty($profile)) {
1232 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
1234 $photo = $profile['photo'];
1235 unset($profile['photo']);
1236 unset($profile['baseurl']);
1238 $profile['nurl'] = normalise_link($profile['url']);
1239 DBA::update('contact', $profile, ['id' => $cid]);
1241 Contact::updateAvatar($photo, $uid, $cid);
1244 private static function switchContacts($receivers, $actor)
1246 if (empty($actor)) {
1250 foreach ($receivers as $receiver) {
1251 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
1252 if (DBA::isResult($contact)) {
1253 self::switchContact($contact['id'], $receiver, $actor);
1256 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
1257 if (DBA::isResult($contact)) {
1258 self::switchContact($contact['id'], $receiver, $actor);
1263 private static function addActivityFields($object_data, $activity)
1265 if (!empty($activity['published']) && empty($object_data['published'])) {
1266 $object_data['published'] = $activity['published'];
1269 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1270 $object_data['updated'] = $activity['updated'];
1273 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1274 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1277 if (!empty($activity['instrument'])) {
1278 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1280 return $object_data;
1283 private static function fetchObject($object_id, $object = [], $trust_source = false)
1285 if (!$trust_source || is_string($object)) {
1286 $data = self::fetchContent($object_id);
1288 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
1291 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
1294 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
1298 if (is_string($data)) {
1299 $item = Item::selectFirst([], ['uri' => $data]);
1300 if (!DBA::isResult($item)) {
1301 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1304 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
1305 $data = self::CreateNote($item);
1308 if (empty($data['type'])) {
1309 logger('Empty type', LOGGER_DEBUG);
1313 switch ($data['type']) {
1317 return self::ProcessObject($data);
1320 if (empty($data['object'])) {
1323 return self::fetchObject($data['object']);
1330 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1335 private static function ProcessObject(&$object)
1337 if (empty($object['id'])) {
1342 $object_data['object_type'] = $object['type'];
1343 $object_data['id'] = $object['id'];
1345 if (!empty($object['inReplyTo'])) {
1346 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1348 $object_data['reply-to-id'] = $object_data['id'];
1351 $object_data['published'] = defaults($object, 'published', null);
1352 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1354 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1355 $object_data['published'] = $object_data['updated'];
1358 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
1359 if (empty($actor)) {
1360 $actor = defaults($object, 'actor', null);
1363 $object_data['uuid'] = defaults($object, 'uuid', null);
1364 $object_data['owner'] = $object_data['author'] = $actor;
1365 $object_data['context'] = defaults($object, 'context', null);
1366 $object_data['conversation'] = defaults($object, 'conversation', null);
1367 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1368 $object_data['name'] = defaults($object, 'title', null);
1369 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1370 $object_data['summary'] = defaults($object, 'summary', null);
1371 $object_data['content'] = defaults($object, 'content', null);
1372 $object_data['source'] = defaults($object, 'source', null);
1373 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1374 $object_data['attachments'] = defaults($object, 'attachment', null);
1375 $object_data['tags'] = defaults($object, 'tag', null);
1376 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1377 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1378 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1380 // Common object data:
1383 // @context, type, actor, signature, mediaType, duration, replies, icon
1385 // Also missing: (Defined in the standard, but currently unused)
1386 // audience, preview, endTime, startTime, generator, image
1391 // emoji, atomUri, inReplyToAtomUri
1394 // contentMap, announcement_count, announcements, context_id, likes, like_count
1395 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1400 // category, licence, language, commentsEnabled
1403 // views, waitTranscoding, state, support, subtitleLanguage
1404 // likes, dislikes, shares, comments
1407 return $object_data;
1410 private static function convertMentions($body)
1412 $URLSearchString = "^\[\]";
1413 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1418 private static function constructTagList($tags, $sensitive)
1425 foreach ($tags as $tag) {
1426 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1427 if (!empty($tag_text)) {
1431 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1435 /// @todo add nsfw for $sensitive
1440 private static function constructAttachList($attachments, $item)
1442 if (empty($attachments)) {
1446 foreach ($attachments as $attach) {
1447 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1448 if ($filetype == 'image') {
1449 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1451 if (!empty($item["attach"])) {
1452 $item["attach"] .= ',';
1454 $item["attach"] = '';
1456 if (!isset($attach['length'])) {
1457 $attach['length'] = "0";
1459 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1466 private static function createItem($activity, $body)
1469 $item['verb'] = ACTIVITY_POST;
1470 $item['parent-uri'] = $activity['reply-to-id'];
1472 if ($activity['reply-to-id'] == $activity['id']) {
1473 $item['gravity'] = GRAVITY_PARENT;
1474 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1476 $item['gravity'] = GRAVITY_COMMENT;
1477 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1480 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
1481 logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
1482 self::fetchMissingActivity($activity['reply-to-id'], $activity);
1485 self::postItem($activity, $item, $body);
1488 private static function likeItem($activity, $body)
1491 $item['verb'] = ACTIVITY_LIKE;
1492 $item['parent-uri'] = $activity['object'];
1493 $item['gravity'] = GRAVITY_ACTIVITY;
1494 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1496 self::postItem($activity, $item, $body);
1499 private static function dislikeItem($activity, $body)
1502 $item['verb'] = ACTIVITY_DISLIKE;
1503 $item['parent-uri'] = $activity['object'];
1504 $item['gravity'] = GRAVITY_ACTIVITY;
1505 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1507 self::postItem($activity, $item, $body);
1510 private static function postItem($activity, $item, $body)
1512 /// @todo What to do with $activity['context']?
1514 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
1515 logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
1519 $item['network'] = Protocol::ACTIVITYPUB;
1520 $item['private'] = !in_array(0, $activity['receiver']);
1521 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1522 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1523 $item['uri'] = $activity['id'];
1524 $item['created'] = $activity['published'];
1525 $item['edited'] = $activity['updated'];
1526 $item['guid'] = $activity['uuid'];
1527 $item['title'] = HTML::toBBCode($activity['name']);
1528 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1529 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1530 $item['location'] = $activity['location'];
1531 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1532 $item['app'] = $activity['service'];
1533 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1535 $item = self::constructAttachList($activity['attachments'], $item);
1537 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1538 if (!empty($source)) {
1539 $item['body'] = $source;
1542 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1543 $item['source'] = $body;
1544 $item['conversation-href'] = $activity['context'];
1545 $item['conversation-uri'] = $activity['conversation'];
1547 foreach ($activity['receiver'] as $receiver) {
1548 $item['uid'] = $receiver;
1549 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1551 if (($receiver != 0) && empty($item['contact-id'])) {
1552 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1555 $item_id = Item::insert($item);
1556 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1560 private static function fetchMissingActivity($url, $child)
1562 if (Config::get('system', 'ostatus_full_threads')) {
1566 $object = ActivityPub::fetchContent($url);
1567 if (empty($object)) {
1568 logger('Activity ' . $url . ' was not fetchable, aborting.');
1573 $activity['@context'] = $object['@context'];
1574 unset($object['@context']);
1575 $activity['id'] = $object['id'];
1576 $activity['to'] = defaults($object, 'to', []);
1577 $activity['cc'] = defaults($object, 'cc', []);
1578 $activity['actor'] = $child['author'];
1579 $activity['object'] = $object;
1580 $activity['published'] = $object['published'];
1581 $activity['type'] = 'Create';
1583 self::processActivity($activity);
1584 logger('Activity ' . $url . ' had been fetched and processed.');
1587 private static function getUserOfObject($object)
1589 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1590 if (!DBA::isResult($self)) {
1593 return $self['uid'];
1597 private static function followUser($activity)
1599 $actor = JsonLD::fetchElement($activity, 'object', 'id');
1600 $uid = self::getUserOfObject($actor);
1605 $owner = User::getOwnerDataById($uid);
1607 $cid = Contact::getIdForURL($activity['owner'], $uid);
1609 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1614 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1615 'author-link' => $activity['owner']];
1617 Contact::addRelationship($owner, $contact, $item);
1618 $cid = Contact::getIdForURL($activity['owner'], $uid);
1623 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1624 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1625 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1628 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1629 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1632 private static function updatePerson($activity)
1634 if (empty($activity['object']['id'])) {
1638 logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
1639 self::fetchprofile($activity['object']['id'], true);
1642 private static function acceptFollowUser($activity)
1644 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1645 $uid = self::getUserOfObject($actor);
1650 $owner = User::getOwnerDataById($uid);
1652 $cid = Contact::getIdForURL($activity['owner'], $uid);
1654 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1658 $fields = ['pending' => false];
1660 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1661 if ($contact['rel'] == Contact::FOLLOWER) {
1662 $fields['rel'] = Contact::FRIEND;
1665 $condition = ['id' => $cid];
1666 DBA::update('contact', $fields, $condition);
1667 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1670 private static function undoActivity($activity)
1672 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
1673 if (empty($activity_url)) {
1677 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1678 if (empty($actor)) {
1682 $author_id = Contact::getIdForURL($actor);
1683 if (empty($author_id)) {
1687 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1690 private static function undoFollowUser($activity)
1692 $object = JsonLD::fetchElement($activity, 'object', 'object');
1693 $uid = self::getUserOfObject($object);
1698 $owner = User::getOwnerDataById($uid);
1700 $cid = Contact::getIdForURL($activity['owner'], $uid);
1702 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1706 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1707 if (!DBA::isResult($contact)) {
1711 Contact::removeFollower($owner, $contact);
1712 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);