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
69 * - Queueing unsucessful deliveries
70 * - Polling the outboxes for missing content?
71 * - Checking signature fails
72 * - Possibly using the LD-JSON parser
76 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
77 const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
78 ['ostatus' => 'http://ostatus.org#', 'uuid' => 'http://schema.org/identifier',
79 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
80 'atomUri' => 'ostatus:atomUri', 'conversation' => 'ostatus:conversation',
81 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']];
83 public static function isRequest()
85 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
86 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
89 public static function getFollowers($owner, $page = null)
91 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
92 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
93 $count = DBA::count('contact', $condition);
95 $data = ['@context' => self::CONTEXT];
96 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
97 $data['type'] = 'OrderedCollection';
98 $data['totalItems'] = $count;
100 // When we hide our friends we will only show the pure number but don't allow more.
101 $profile = Profile::getProfileForUser($owner['uid']);
102 if (!empty($profile['hide-friends'])) {
107 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
111 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
112 while ($contact = DBA::fetch($contacts)) {
113 $list[] = $contact['url'];
117 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
120 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
122 $data['orderedItems'] = $list;
128 public static function getFollowing($owner, $page = null)
130 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
131 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
132 $count = DBA::count('contact', $condition);
134 $data = ['@context' => self::CONTEXT];
135 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
136 $data['type'] = 'OrderedCollection';
137 $data['totalItems'] = $count;
139 // When we hide our friends we will only show the pure number but don't allow more.
140 $profile = Profile::getProfileForUser($owner['uid']);
141 if (!empty($profile['hide-friends'])) {
146 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
150 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
151 while ($contact = DBA::fetch($contacts)) {
152 $list[] = $contact['url'];
156 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
159 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
161 $data['orderedItems'] = $list;
167 public static function getOutbox($owner, $page = null)
169 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
171 $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
172 'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
173 'deleted' => false, 'visible' => true];
174 $count = DBA::count('item', $condition);
176 $data = ['@context' => self::CONTEXT];
177 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
178 $data['type'] = 'OrderedCollection';
179 $data['totalItems'] = $count;
182 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
186 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
188 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
189 while ($item = Item::fetch($items)) {
190 $object = self::createObjectFromItemID($item['id']);
191 unset($object['@context']);
196 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
199 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
201 $data['orderedItems'] = $list;
208 * Return the ActivityPub profile of the given user
210 * @param integer $uid User ID
213 public static function profile($uid)
215 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
216 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
217 'account_removed' => false, 'verified' => true];
218 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
219 $user = DBA::selectFirst('user', $fields, $condition);
220 if (!DBA::isResult($user)) {
224 $fields = ['locality', 'region', 'country-name'];
225 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
226 if (!DBA::isResult($profile)) {
230 $fields = ['name', 'url', 'location', 'about', 'avatar'];
231 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
232 if (!DBA::isResult($contact)) {
236 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
237 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
238 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
240 $data['id'] = $contact['url'];
241 $data['uuid'] = $user['guid'];
242 $data['type'] = $accounttype[$user['account-type']];
243 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
244 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
245 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
246 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
247 $data['preferredUsername'] = $user['nickname'];
248 $data['name'] = $contact['name'];
249 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
250 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
251 $data['summary'] = $contact['about'];
252 $data['url'] = $contact['url'];
253 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
254 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
255 'owner' => $contact['url'],
256 'publicKeyPem' => $user['pubkey']];
257 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
258 $data['icon'] = ['type' => 'Image',
259 'url' => $contact['avatar']];
261 // tags: https://kitty.town/@inmysocks/100656097926961126.json
265 private static function fetchPermissionBlockFromConversation($item)
267 if (empty($item['thr-parent'])) {
271 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
272 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
273 if (!DBA::isResult($conversation)) {
277 $activity = json_decode($conversation['source'], true);
279 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
280 $profile = ActivityPub::fetchprofile($actor);
282 $item_profile = ActivityPub::fetchprofile($item['author-link']);
283 $exclude[] = $item['author-link'];
285 if ($item['gravity'] == GRAVITY_PARENT) {
286 $exclude[] = $item['owner-link'];
289 $permissions['to'][] = $actor;
291 $elements = ['to', 'cc', 'bto', 'bcc'];
292 foreach ($elements as $element) {
293 if (empty($activity[$element])) {
296 if (is_string($activity[$element])) {
297 $activity[$element] = [$activity[$element]];
300 foreach ($activity[$element] as $receiver) {
301 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
302 $receiver = $item_profile['followers'];
304 if (!in_array($receiver, $exclude)) {
305 $permissions[$element][] = $receiver;
312 public static function createPermissionBlockForItem($item)
314 $data = ['to' => [], 'cc' => []];
316 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
318 $actor_profile = ActivityPub::fetchprofile($item['author-link']);
320 $terms = Term::tagArrayFromItemId($item['id']);
322 $contacts[$item['author-link']] = $item['author-link'];
324 if (!$item['private']) {
325 $data['to'][] = self::PUBLIC;
326 if (!empty($actor_profile['followers'])) {
327 $data['cc'][] = $actor_profile['followers'];
330 foreach ($terms as $term) {
331 if ($term['type'] != TERM_MENTION) {
334 $profile = self::fetchprofile($term['url'], false);
335 if (!empty($profile) && empty($contacts[$profile['url']])) {
336 $data['cc'][] = $profile['url'];
337 $contacts[$profile['url']] = $profile['url'];
341 $receiver_list = Item::enumeratePermissions($item);
345 foreach ($terms as $term) {
346 if ($term['type'] != TERM_MENTION) {
349 $cid = Contact::getIdForURL($term['url'], $item['uid']);
350 if (!empty($cid) && in_array($cid, $receiver_list)) {
351 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
352 $data['to'][] = $contact['url'];
353 $contacts[$contact['url']] = $contact['url'];
357 foreach ($receiver_list as $receiver) {
358 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
359 if (empty($contacts[$contact['url']])) {
360 $data['cc'][] = $contact['url'];
361 $contacts[$contact['url']] = $contact['url'];
366 $parents = Item::select(['author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
367 while ($parent = Item::fetch($parents)) {
368 // Don't include data from future posts
369 if ($parent['id'] >= $item['id']) {
373 $profile = self::fetchprofile($parent['author-link'], false);
374 if (!empty($profile) && empty($contacts[$profile['url']])) {
375 $data['cc'][] = $profile['url'];
376 $contacts[$profile['url']] = $profile['url'];
379 if ($item['gravity'] != GRAVITY_PARENT) {
383 $profile = self::fetchprofile($parent['owner-link'], false);
384 if (!empty($profile) && empty($contacts[$profile['url']])) {
385 $data['cc'][] = $profile['url'];
386 $contacts[$profile['url']] = $profile['url'];
389 DBA::close($parents);
391 if (empty($data['to'])) {
392 $data['to'] = $data['cc'];
399 public static function fetchTargetInboxes($item, $uid)
401 $permissions = self::createPermissionBlockForItem($item);
402 if (empty($permissions)) {
408 if ($item['gravity'] == GRAVITY_ACTIVITY) {
409 $item_profile = ActivityPub::fetchprofile($item['author-link']);
411 $item_profile = ActivityPub::fetchprofile($item['owner-link']);
414 $elements = ['to', 'cc', 'bto', 'bcc'];
415 foreach ($elements as $element) {
416 if (empty($permissions[$element])) {
420 foreach ($permissions[$element] as $receiver) {
421 if ($receiver == $item_profile['followers']) {
422 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
423 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
424 while ($contact = DBA::fetch($contacts)) {
425 $contact = defaults($contact, 'batch', $contact['notify']);
426 $inboxes[$contact] = $contact;
428 DBA::close($contacts);
430 $profile = self::fetchprofile($receiver);
431 if (!empty($profile)) {
432 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
433 $inboxes[$target] = $target;
442 public static function getTypeOfItem($item)
444 if ($item['verb'] == ACTIVITY_POST) {
445 if ($item['created'] == $item['edited']) {
450 } elseif ($item['verb'] == ACTIVITY_LIKE) {
452 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
454 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
456 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
458 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
459 $type = 'TentativeAccept';
467 public static function createActivityFromItem($item_id, $object_mode = false)
469 $item = Item::selectFirst([], ['id' => $item_id]);
471 if (!DBA::isResult($item)) {
475 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
476 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
477 if (DBA::isResult($conversation)) {
478 $data = json_decode($conversation['source']);
484 $type = self::getTypeOfItem($item);
487 $data = ['@context' => self::CONTEXT];
489 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
491 } elseif ($item['deleted']) {
498 $data['id'] = $item['uri'] . '#' . $type;
499 $data['type'] = $type;
500 $data['actor'] = $item['author-link'];
502 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
504 if ($item["created"] != $item["edited"]) {
505 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
508 $data['context'] = self::createConversationURLFromItem($item);
510 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
512 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
513 $data['object'] = self::CreateNote($item);
514 } elseif ($data['type'] == 'Undo') {
515 $data['object'] = self::createActivityFromItem($item_id, true);
517 $data['object'] = $item['thr-parent'];
520 $owner = User::getOwnerDataById($item['uid']);
523 return LDSignature::sign($data, $owner);
529 public static function createObjectFromItemID($item_id)
531 $item = Item::selectFirst([], ['id' => $item_id]);
533 if (!DBA::isResult($item)) {
537 $data = ['@context' => self::CONTEXT];
538 $data = array_merge($data, self::CreateNote($item));
543 private static function createTagList($item)
547 $terms = Term::tagArrayFromItemId($item['id']);
548 foreach ($terms as $term) {
549 if ($term['type'] == TERM_MENTION) {
550 $contact = Contact::getDetailsByURL($term['url']);
551 if (!empty($contact['addr'])) {
552 $mention = '@' . $contact['addr'];
554 $mention = '@' . $term['url'];
557 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
563 private static function createConversationURLFromItem($item)
565 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
566 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
567 $conversation_uri = $conversation['conversation-uri'];
569 $conversation_uri = $item['parent-uri'];
571 return $conversation_uri;
574 private static function CreateNote($item)
576 if (!empty($item['title'])) {
582 if ($item['deleted']) {
587 $data['id'] = $item['uri'];
588 $data['type'] = $type;
590 if ($item['deleted']) {
594 $data['summary'] = null; // Ignore by now
596 if ($item['uri'] != $item['thr-parent']) {
597 $data['inReplyTo'] = $item['thr-parent'];
599 $data['inReplyTo'] = null;
602 $data['uuid'] = $item['guid'];
603 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
605 if ($item["created"] != $item["edited"]) {
606 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
609 $data['url'] = $item['plink'];
610 $data['attributedTo'] = $item['author-link'];
611 $data['actor'] = $item['author-link'];
612 $data['sensitive'] = false; // - Query NSFW
613 $data['conversation'] = $data['context'] = self::createConversationURLFromItem($item);
615 if (!empty($item['title'])) {
616 $data['name'] = BBCode::convert($item['title'], false, 7);
619 $data['content'] = BBCode::convert($item['body'], false, 7);
620 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
621 $data['attachment'] = []; // @ToDo
622 $data['tag'] = self::createTagList($item);
623 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
625 //$data['emoji'] = []; // Ignore by now
629 public static function transmitActivity($activity, $target, $uid)
631 $profile = self::fetchprofile($target);
633 $owner = User::getOwnerDataById($uid);
635 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
636 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
638 'actor' => $owner['url'],
639 'object' => $profile['url'],
640 'to' => $profile['url']];
642 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
644 $signed = LDSignature::sign($data, $owner);
645 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
648 public static function transmitContactAccept($target, $id, $uid)
650 $profile = self::fetchprofile($target);
652 $owner = User::getOwnerDataById($uid);
653 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
654 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
656 'actor' => $owner['url'],
657 'object' => ['id' => $id, 'type' => 'Follow',
658 'actor' => $profile['url'],
659 'object' => $owner['url']],
660 'to' => $profile['url']];
662 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
664 $signed = LDSignature::sign($data, $owner);
665 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
668 public static function transmitContactReject($target, $id, $uid)
670 $profile = self::fetchprofile($target);
672 $owner = User::getOwnerDataById($uid);
673 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
674 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
676 'actor' => $owner['url'],
677 'object' => ['id' => $id, 'type' => 'Follow',
678 'actor' => $profile['url'],
679 'object' => $owner['url']],
680 'to' => $profile['url']];
682 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
684 $signed = LDSignature::sign($data, $owner);
685 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
688 public static function transmitContactUndo($target, $uid)
690 $profile = self::fetchprofile($target);
692 $id = System::baseUrl() . '/activity/' . System::createGUID();
694 $owner = User::getOwnerDataById($uid);
695 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
698 'actor' => $owner['url'],
699 'object' => ['id' => $id, 'type' => 'Follow',
700 'actor' => $owner['url'],
701 'object' => $profile['url']],
702 'to' => $profile['url']];
704 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
706 $signed = LDSignature::sign($data, $owner);
707 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
711 * Fetches ActivityPub content from the given url
713 * @param string $url content url
716 public static function fetchContent($url)
718 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
719 if (!$ret['success'] || empty($ret['body'])) {
722 return json_decode($ret['body'], true);
726 * Resolves the profile url from the address by using webfinger
728 * @param string $addr profile address (user@domain.tld)
731 private static function addrToUrl($addr)
733 $addr_parts = explode('@', $addr);
734 if (count($addr_parts) != 2) {
738 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
740 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
741 if (!$ret['success'] || empty($ret['body'])) {
745 $data = json_decode($ret['body'], true);
747 if (empty($data['links'])) {
751 foreach ($data['links'] as $link) {
752 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
756 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
757 return $link['href'];
765 * Fetches a profile form a given url
767 * @param string $url profile url
768 * @param boolean $update true = always update, false = never update, null = update when not found
769 * @return array profile array
771 public static function fetchprofile($url, $update = null)
777 if (empty($update)) {
778 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
779 if (DBA::isResult($apcontact)) {
783 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
784 if (DBA::isResult($apcontact)) {
788 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
789 if (DBA::isResult($apcontact)) {
793 if (!is_null($update)) {
798 if (empty(parse_url($url, PHP_URL_SCHEME))) {
799 $url = self::addrToUrl($url);
805 $data = self::fetchContent($url);
807 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
812 $apcontact['url'] = $data['id'];
813 $apcontact['uuid'] = defaults($data, 'uuid', null);
814 $apcontact['type'] = defaults($data, 'type', null);
815 $apcontact['following'] = defaults($data, 'following', null);
816 $apcontact['followers'] = defaults($data, 'followers', null);
817 $apcontact['inbox'] = defaults($data, 'inbox', null);
818 $apcontact['outbox'] = defaults($data, 'outbox', null);
819 $apcontact['sharedinbox'] = JsonLD::fetchElement($data, 'endpoints', 'sharedInbox');
820 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
821 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
822 $apcontact['about'] = defaults($data, 'summary', '');
823 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon', 'url');
824 $apcontact['alias'] = JsonLD::fetchElement($data, 'url', 'href');
826 $parts = parse_url($apcontact['url']);
827 unset($parts['scheme']);
828 unset($parts['path']);
829 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
831 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data, 'publicKey', 'publicKeyPem'));
834 // manuallyApprovesFollowers
837 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
839 // Unhandled from Misskey
840 // sharedInbox, isCat
842 // Unhandled from Kroeg
843 // kroeg:blocks, updated
845 // Check if the address is resolvable
846 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
847 $parts = parse_url($apcontact['url']);
848 unset($parts['path']);
849 $apcontact['baseurl'] = Network::unparseURL($parts);
851 $apcontact['addr'] = null;
854 if ($apcontact['url'] == $apcontact['alias']) {
855 $apcontact['alias'] = null;
858 $apcontact['updated'] = DateTimeFormat::utcNow();
860 DBA::update('apcontact', $apcontact, ['url' => $url], true);
862 // Update some data in the contact table with various ways to catch them all
863 $contact_fields = ['name' => $apcontact['name'], 'about' => $apcontact['about']];
864 DBA::update('contact', $contact_fields, ['nurl' => normalise_link($url)]);
866 $contacts = DBA::select('contact', ['uid', 'id'], ['nurl' => normalise_link($url)]);
867 while ($contact = DBA::fetch($contacts)) {
868 Contact::updateAvatar($apcontact['photo'], $contact['uid'], $contact['id']);
870 DBA::close($contacts);
872 // Update the gcontact table
873 DBA::update('gcontact', $contact_fields, ['nurl' => normalise_link($url)]);
879 * Fetches a profile from the given url into an array that is compatible to Probe::uri
881 * @param string $url profile url
884 public static function probeProfile($url)
886 $apcontact = self::fetchprofile($url, true);
887 if (empty($apcontact)) {
891 $profile = ['network' => Protocol::ACTIVITYPUB];
892 $profile['nick'] = $apcontact['nick'];
893 $profile['name'] = $apcontact['name'];
894 $profile['guid'] = $apcontact['uuid'];
895 $profile['url'] = $apcontact['url'];
896 $profile['addr'] = $apcontact['addr'];
897 $profile['alias'] = $apcontact['alias'];
898 $profile['photo'] = $apcontact['photo'];
899 // $profile['community']
900 // $profile['keywords']
901 // $profile['location']
902 $profile['about'] = $apcontact['about'];
903 $profile['batch'] = $apcontact['sharedinbox'];
904 $profile['notify'] = $apcontact['inbox'];
905 $profile['poll'] = $apcontact['outbox'];
906 $profile['pubkey'] = $apcontact['pubkey'];
907 $profile['baseurl'] = $apcontact['baseurl'];
909 // Remove all "null" fields
910 foreach ($profile as $field => $content) {
911 if (is_null($content)) {
912 unset($profile[$field]);
919 public static function processInbox($body, $header, $uid)
921 $http_signer = HTTPSignature::getSigner($body, $header);
922 if (empty($http_signer)) {
923 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
926 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
929 $activity = json_decode($body, true);
931 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
932 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
934 if (empty($activity)) {
935 logger('Invalid body.', LOGGER_DEBUG);
939 if (LDSignature::isSigned($activity)) {
940 $ld_signer = LDSignature::getSigner($activity);
941 if (!empty($ld_signer && ($actor == $http_signer))) {
942 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
943 $trust_source = true;
944 } elseif (!empty($ld_signer)) {
945 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
946 $trust_source = true;
947 } elseif ($actor == $http_signer) {
948 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
949 $trust_source = true;
951 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
952 $trust_source = false;
954 } elseif ($actor == $http_signer) {
955 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
956 $trust_source = true;
958 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
959 $trust_source = false;
962 self::processActivity($activity, $body, $uid, $trust_source);
965 public static function fetchOutbox($url, $uid)
967 $data = self::fetchContent($url);
972 if (!empty($data['orderedItems'])) {
973 $items = $data['orderedItems'];
974 } elseif (!empty($data['first']['orderedItems'])) {
975 $items = $data['first']['orderedItems'];
976 } elseif (!empty($data['first'])) {
977 self::fetchOutbox($data['first'], $uid);
983 foreach ($items as $activity) {
984 self::processActivity($activity, '', $uid, true);
988 private static function prepareObjectData($activity, $uid, &$trust_source)
990 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
992 logger('Empty actor', LOGGER_DEBUG);
996 // Fetch all receivers from to, cc, bto and bcc
997 $receivers = self::getReceivers($activity, $actor);
999 // When it is a delivery to a personal inbox we add that user to the receivers
1001 $owner = User::getOwnerDataById($uid);
1002 $additional = ['uid:' . $uid => $uid];
1003 $receivers = array_merge($receivers, $additional);
1006 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
1008 if (is_string($activity['object'])) {
1009 $object_url = $activity['object'];
1010 } elseif (!empty($activity['object']['id'])) {
1011 $object_url = $activity['object']['id'];
1013 logger('No object found', LOGGER_DEBUG);
1017 // Fetch the content only on activities where this matters
1018 if (in_array($activity['type'], ['Create', 'Announce'])) {
1019 $object_data = self::fetchObject($object_url, $activity['object'], $trust_source);
1020 if (empty($object_data)) {
1021 logger("Object data couldn't be processed", LOGGER_DEBUG);
1024 // We had been able to retrieve the object data - so we can trust the source
1025 $trust_source = true;
1026 } elseif ($activity['type'] == 'Update') {
1028 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1029 $object_data['object'] = $activity['object'];
1030 } elseif ($activity['type'] == 'Accept') {
1032 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1033 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'actor');
1034 } elseif ($activity['type'] == 'Undo') {
1036 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1037 if ($object_data['object_type'] == 'Follow') {
1038 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'object');
1040 $object_data['object'] = $activity['object'];
1042 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
1043 // Create a mostly empty array out of the activity data (instead of the object).
1044 // This way we later don't have to check for the existence of ech individual array element.
1045 $object_data = self::processCommonData($activity);
1046 $object_data['name'] = $activity['type'];
1047 $object_data['author'] = $activity['actor'];
1048 $object_data['object'] = $object_url;
1049 } elseif ($activity['type'] == 'Follow') {
1050 $object_data['id'] = $activity['id'];
1051 $object_data['object'] = $object_url;
1056 $object_data = self::addActivityFields($object_data, $activity);
1058 $object_data['type'] = $activity['type'];
1059 $object_data['owner'] = $actor;
1060 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
1062 return $object_data;
1065 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
1067 if (empty($activity['type'])) {
1068 logger('Empty type', LOGGER_DEBUG);
1072 if (empty($activity['object'])) {
1073 logger('Empty object', LOGGER_DEBUG);
1077 if (empty($activity['actor'])) {
1078 logger('Empty actor', LOGGER_DEBUG);
1084 // title, atomUri, context_id, statusnetConversationId
1087 // context, location, signature;
1089 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
1091 // $trust_source is called by reference and is set to true if the content was retrieved successfully
1092 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
1093 if (empty($object_data)) {
1094 logger('No object data found', LOGGER_DEBUG);
1098 if (!$trust_source) {
1099 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
1102 switch ($activity['type']) {
1105 self::createItem($object_data, $body);
1109 self::likeItem($object_data, $body);
1113 self::dislikeItem($object_data, $body);
1117 if (in_array($object_data['object_type'], ['Person', 'Organization', 'Service', 'Group', 'Application'])) {
1118 self::updatePerson($object_data, $body);
1126 self::followUser($object_data);
1130 if ($object_data['object_type'] == 'Follow') {
1131 self::acceptFollowUser($object_data);
1136 if ($object_data['object_type'] == 'Follow') {
1137 self::undoFollowUser($object_data);
1138 } elseif (in_array($object_data['object_type'], ['Like', 'Dislike', 'Accept', 'Reject', 'TentativeAccept'])) {
1139 self::undoActivity($object_data);
1144 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
1149 private static function getReceivers($activity, $actor)
1153 // When it is an answer, we inherite the receivers from the parent
1154 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1155 if (!empty($replyto)) {
1156 $parents = Item::select(['uid'], ['uri' => $replyto]);
1157 while ($parent = Item::fetch($parents)) {
1158 $receivers['uid:' . $parent['uid']] = $parent['uid'];
1162 if (!empty($actor)) {
1163 $profile = self::fetchprofile($actor);
1164 $followers = defaults($profile, 'followers', '');
1166 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
1168 logger('Empty actor', LOGGER_DEBUG);
1172 $elements = ['to', 'cc', 'bto', 'bcc'];
1173 foreach ($elements as $element) {
1174 if (empty($activity[$element])) {
1178 // The receiver can be an arror or a string
1179 if (is_string($activity[$element])) {
1180 $activity[$element] = [$activity[$element]];
1183 foreach ($activity[$element] as $receiver) {
1184 if ($receiver == self::PUBLIC) {
1185 $receivers['uid:0'] = 0;
1188 if (($receiver == self::PUBLIC) && !empty($actor)) {
1189 // This will most likely catch all OStatus connections to Mastodon
1190 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1191 $contacts = DBA::select('contact', ['uid'], $condition);
1192 while ($contact = DBA::fetch($contacts)) {
1193 if ($contact['uid'] != 0) {
1194 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1197 DBA::close($contacts);
1200 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1201 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1202 'network' => Protocol::ACTIVITYPUB];
1203 $contacts = DBA::select('contact', ['uid'], $condition);
1204 while ($contact = DBA::fetch($contacts)) {
1205 if ($contact['uid'] != 0) {
1206 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1209 DBA::close($contacts);
1213 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1214 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1215 if (!DBA::isResult($contact)) {
1218 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1222 self::switchContacts($receivers, $actor);
1227 private static function switchContact($cid, $uid, $url)
1229 $profile = ActivityPub::probeProfile($url);
1230 if (empty($profile)) {
1234 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
1236 $photo = $profile['photo'];
1237 unset($profile['photo']);
1238 unset($profile['baseurl']);
1240 $profile['nurl'] = normalise_link($profile['url']);
1241 DBA::update('contact', $profile, ['id' => $cid]);
1243 Contact::updateAvatar($photo, $uid, $cid);
1246 private static function switchContacts($receivers, $actor)
1248 if (empty($actor)) {
1252 foreach ($receivers as $receiver) {
1253 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
1254 if (DBA::isResult($contact)) {
1255 self::switchContact($contact['id'], $receiver, $actor);
1258 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
1259 if (DBA::isResult($contact)) {
1260 self::switchContact($contact['id'], $receiver, $actor);
1265 private static function addActivityFields($object_data, $activity)
1267 if (!empty($activity['published']) && empty($object_data['published'])) {
1268 $object_data['published'] = $activity['published'];
1271 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1272 $object_data['updated'] = $activity['updated'];
1275 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1276 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1279 if (!empty($activity['instrument'])) {
1280 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1282 return $object_data;
1285 private static function fetchObject($object_url, $object = [], $trust_source = false)
1287 if (!$trust_source || is_string($object)) {
1288 $data = self::fetchContent($object_url);
1290 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1291 $data = $object_url;
1293 logger('Fetched content for ' . $object_url, LOGGER_DEBUG);
1296 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1300 if (is_string($data)) {
1301 $item = Item::selectFirst([], ['uri' => $data]);
1302 if (!DBA::isResult($item)) {
1303 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1306 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1307 $data = self::CreateNote($item);
1310 if (empty($data['type'])) {
1311 logger('Empty type', LOGGER_DEBUG);
1314 $type = $data['type'];
1315 logger('Type ' . $type, LOGGER_DEBUG);
1318 if (in_array($type, ['Note', 'Article', 'Video'])) {
1319 $common = self::processCommonData($data);
1324 return array_merge($common, self::processNote($data));
1326 return array_merge($common, self::processArticle($data));
1328 return array_merge($common, self::processVideo($data));
1331 if (empty($data['object'])) {
1334 return self::fetchObject($data['object']);
1341 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1346 private static function processCommonData(&$object)
1348 if (empty($object['id'])) {
1353 $object_data['type'] = $object['type'];
1354 $object_data['uri'] = $object['id'];
1356 if (!empty($object['inReplyTo'])) {
1357 $object_data['reply-to-uri'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1359 $object_data['reply-to-uri'] = $object_data['uri'];
1362 $object_data['published'] = defaults($object, 'published', null);
1363 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1365 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1366 $object_data['published'] = $object_data['updated'];
1369 $object_data['uuid'] = defaults($object, 'uuid', null);
1370 $object_data['owner'] = $object_data['author'] = JsonLD::fetchElement($object, 'attributedTo', 'id');
1371 $object_data['context'] = defaults($object, 'context', null);
1372 $object_data['conversation'] = defaults($object, 'conversation', null);
1373 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1374 $object_data['name'] = defaults($object, 'title', null);
1375 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1376 $object_data['summary'] = defaults($object, 'summary', null);
1377 $object_data['content'] = defaults($object, 'content', null);
1378 $object_data['source'] = defaults($object, 'source', null);
1379 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1380 $object_data['attachments'] = defaults($object, 'attachment', null);
1381 $object_data['tags'] = defaults($object, 'tag', null);
1382 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1383 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1384 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1387 // @context, type, actor, signature, mediaType, duration, replies, icon
1389 // Also missing: (Defined in the standard, but currently unused)
1390 // audience, preview, endTime, startTime, generator, image
1392 return $object_data;
1395 private static function processNote($object)
1400 // emoji, atomUri, inReplyToAtomUri
1403 // contentMap, announcement_count, announcements, context_id, likes, like_count
1404 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1406 return $object_data;
1409 private static function processArticle($object)
1413 return $object_data;
1416 private static function processVideo($object)
1421 // category, licence, language, commentsEnabled
1424 // views, waitTranscoding, state, support, subtitleLanguage
1425 // likes, dislikes, shares, comments
1427 return $object_data;
1430 private static function convertMentions($body)
1432 $URLSearchString = "^\[\]";
1433 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1438 private static function constructTagList($tags, $sensitive)
1445 foreach ($tags as $tag) {
1446 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1447 if (!empty($tag_text)) {
1451 if (empty($tag['href'])) {
1456 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1460 /// @todo add nsfw for $sensitive
1465 private static function constructAttachList($attachments, $item)
1467 if (empty($attachments)) {
1471 foreach ($attachments as $attach) {
1472 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1473 if ($filetype == 'image') {
1474 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1476 if (!empty($item["attach"])) {
1477 $item["attach"] .= ',';
1479 $item["attach"] = '';
1481 if (!isset($attach['length'])) {
1482 $attach['length'] = "0";
1484 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1491 private static function createItem($activity, $body)
1494 $item['verb'] = ACTIVITY_POST;
1495 $item['parent-uri'] = $activity['reply-to-uri'];
1497 if ($activity['reply-to-uri'] == $activity['uri']) {
1498 $item['gravity'] = GRAVITY_PARENT;
1499 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1501 $item['gravity'] = GRAVITY_COMMENT;
1502 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1505 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1506 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1507 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1510 self::postItem($activity, $item, $body);
1513 private static function likeItem($activity, $body)
1516 $item['verb'] = ACTIVITY_LIKE;
1517 $item['parent-uri'] = $activity['object'];
1518 $item['gravity'] = GRAVITY_ACTIVITY;
1519 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1521 self::postItem($activity, $item, $body);
1524 private static function dislikeItem($activity, $body)
1527 $item['verb'] = ACTIVITY_DISLIKE;
1528 $item['parent-uri'] = $activity['object'];
1529 $item['gravity'] = GRAVITY_ACTIVITY;
1530 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1532 self::postItem($activity, $item, $body);
1535 private static function postItem($activity, $item, $body)
1537 /// @todo What to do with $activity['context']?
1539 $item['network'] = Protocol::ACTIVITYPUB;
1540 $item['private'] = !in_array(0, $activity['receiver']);
1541 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1542 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1543 $item['uri'] = $activity['uri'];
1544 $item['created'] = $activity['published'];
1545 $item['edited'] = $activity['updated'];
1546 $item['guid'] = $activity['uuid'];
1547 $item['title'] = HTML::toBBCode($activity['name']);
1548 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1549 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1550 $item['location'] = $activity['location'];
1551 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1552 $item['app'] = $activity['service'];
1553 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1555 $item = self::constructAttachList($activity['attachments'], $item);
1557 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1558 if (!empty($source)) {
1559 $item['body'] = $source;
1562 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1563 $item['source'] = $body;
1564 $item['conversation-uri'] = $activity['conversation'];
1566 foreach ($activity['receiver'] as $receiver) {
1567 $item['uid'] = $receiver;
1568 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1570 if (($receiver != 0) && empty($item['contact-id'])) {
1571 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1574 $item_id = Item::insert($item);
1575 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1579 private static function fetchMissingActivity($url, $child)
1581 if (Config::get('system', 'ostatus_full_threads')) {
1585 $object = ActivityPub::fetchContent($url);
1586 if (empty($object)) {
1587 logger('Activity ' . $url . ' was not fetchable, aborting.');
1592 $activity['@context'] = $object['@context'];
1593 unset($object['@context']);
1594 $activity['id'] = $object['id'];
1595 $activity['to'] = defaults($object, 'to', []);
1596 $activity['cc'] = defaults($object, 'cc', []);
1597 $activity['actor'] = $child['author'];
1598 $activity['object'] = $object;
1599 $activity['published'] = $object['published'];
1600 $activity['type'] = 'Create';
1602 self::processActivity($activity);
1603 logger('Activity ' . $url . ' had been fetched and processed.');
1606 private static function getUserOfObject($object)
1608 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1609 if (!DBA::isResult($self)) {
1612 return $self['uid'];
1616 private static function followUser($activity)
1618 $uid = self::getUserOfObject($activity['object']);
1623 $owner = User::getOwnerDataById($uid);
1625 $cid = Contact::getIdForURL($activity['owner'], $uid);
1627 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1632 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1633 'author-link' => $activity['owner']];
1635 Contact::addRelationship($owner, $contact, $item);
1636 $cid = Contact::getIdForURL($activity['owner'], $uid);
1641 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1642 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1643 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1646 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1647 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1650 private static function updatePerson($activity)
1652 if (empty($activity['object']['id'])) {
1656 self::fetchprofile($activity['object']['id'], true);
1659 private static function acceptFollowUser($activity)
1661 $uid = self::getUserOfObject($activity['object']);
1666 $owner = User::getOwnerDataById($uid);
1668 $cid = Contact::getIdForURL($activity['owner'], $uid);
1670 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1674 $fields = ['pending' => false];
1676 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1677 if ($contact['rel'] == Contact::FOLLOWER) {
1678 $fields['rel'] = Contact::FRIEND;
1681 $condition = ['id' => $cid];
1682 DBA::update('contact', $fields, $condition);
1683 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1686 private static function undoActivity($activity)
1688 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
1689 if (empty($activity_url)) {
1693 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1694 if (empty($actor)) {
1698 $author_id = Contact::getIdForURL($actor);
1699 if (empty($author_id)) {
1703 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1706 private static function undoFollowUser($activity)
1708 $uid = self::getUserOfObject($activity['object']);
1713 $owner = User::getOwnerDataById($uid);
1715 $cid = Contact::getIdForURL($activity['owner'], $uid);
1717 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1721 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1722 if (!DBA::isResult($contact)) {
1726 Contact::removeFollower($owner, $contact);
1727 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);