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?
74 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
75 const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
76 ['ostatus' => 'http://ostatus.org#', 'uuid' => 'http://schema.org/identifier',
77 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag',
78 'atomUri' => 'ostatus:atomUri', 'conversation' => 'ostatus:conversation',
79 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']];
81 public static function isRequest()
83 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
84 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
87 public static function getFollowers($owner, $page = null)
89 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
90 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
91 $count = DBA::count('contact', $condition);
93 $data = ['@context' => self::CONTEXT];
94 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
95 $data['type'] = 'OrderedCollection';
96 $data['totalItems'] = $count;
98 // When we hide our friends we will only show the pure number but don't allow more.
99 $profile = Profile::getProfileForUser($owner['uid']);
100 if (!empty($profile['hide-friends'])) {
105 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
109 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
110 while ($contact = DBA::fetch($contacts)) {
111 $list[] = $contact['url'];
115 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
118 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
120 $data['orderedItems'] = $list;
126 public static function getFollowing($owner, $page = null)
128 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
129 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
130 $count = DBA::count('contact', $condition);
132 $data = ['@context' => self::CONTEXT];
133 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
134 $data['type'] = 'OrderedCollection';
135 $data['totalItems'] = $count;
137 // When we hide our friends we will only show the pure number but don't allow more.
138 $profile = Profile::getProfileForUser($owner['uid']);
139 if (!empty($profile['hide-friends'])) {
144 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
148 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
149 while ($contact = DBA::fetch($contacts)) {
150 $list[] = $contact['url'];
154 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
157 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
159 $data['orderedItems'] = $list;
165 public static function getOutbox($owner, $page = null)
167 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
169 $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
170 'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
171 'deleted' => false, 'visible' => true];
172 $count = DBA::count('item', $condition);
174 $data = ['@context' => self::CONTEXT];
175 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
176 $data['type'] = 'OrderedCollection';
177 $data['totalItems'] = $count;
180 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
184 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
186 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
187 while ($item = Item::fetch($items)) {
188 $object = self::createObjectFromItemID($item['id']);
189 unset($object['@context']);
194 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
197 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
199 $data['orderedItems'] = $list;
206 * Return the ActivityPub profile of the given user
208 * @param integer $uid User ID
211 public static function profile($uid)
213 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
214 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
215 'account_removed' => false, 'verified' => true];
216 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
217 $user = DBA::selectFirst('user', $fields, $condition);
218 if (!DBA::isResult($user)) {
222 $fields = ['locality', 'region', 'country-name'];
223 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
224 if (!DBA::isResult($profile)) {
228 $fields = ['name', 'url', 'location', 'about', 'avatar'];
229 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
230 if (!DBA::isResult($contact)) {
234 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
235 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
236 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
238 $data['id'] = $contact['url'];
239 $data['uuid'] = $user['guid'];
240 $data['type'] = $accounttype[$user['account-type']];
241 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
242 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
243 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
244 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
245 $data['preferredUsername'] = $user['nickname'];
246 $data['name'] = $contact['name'];
247 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
248 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
249 $data['summary'] = $contact['about'];
250 $data['url'] = $contact['url'];
251 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
252 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
253 'owner' => $contact['url'],
254 'publicKeyPem' => $user['pubkey']];
255 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
256 $data['icon'] = ['type' => 'Image',
257 'url' => $contact['avatar']];
259 // tags: https://kitty.town/@inmysocks/100656097926961126.json
263 private static function fetchPermissionBlockFromConversation($item)
265 if (empty($item['thr-parent'])) {
269 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
270 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
271 if (!DBA::isResult($conversation)) {
275 $activity = json_decode($conversation['source'], true);
277 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
278 $profile = ActivityPub::fetchprofile($actor);
280 $item_profile = ActivityPub::fetchprofile($item['author-link']);
281 $exclude[] = $item['author-link'];
283 if ($item['gravity'] == GRAVITY_PARENT) {
284 $exclude[] = $item['owner-link'];
287 $permissions['to'][] = $actor;
289 $elements = ['to', 'cc', 'bto', 'bcc'];
290 foreach ($elements as $element) {
291 if (empty($activity[$element])) {
294 if (is_string($activity[$element])) {
295 $activity[$element] = [$activity[$element]];
298 foreach ($activity[$element] as $receiver) {
299 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
300 $receiver = $item_profile['followers'];
302 if (!in_array($receiver, $exclude)) {
303 $permissions[$element][] = $receiver;
310 public static function createPermissionBlockForItem($item)
312 $data = ['to' => [], 'cc' => []];
314 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
316 $actor_profile = ActivityPub::fetchprofile($item['author-link']);
318 $terms = Term::tagArrayFromItemId($item['id']);
320 $contacts[$item['author-link']] = $item['author-link'];
322 if (!$item['private']) {
323 $data['to'][] = self::PUBLIC;
324 if (!empty($actor_profile['followers'])) {
325 $data['cc'][] = $actor_profile['followers'];
328 foreach ($terms as $term) {
329 if ($term['type'] != TERM_MENTION) {
332 $profile = self::fetchprofile($term['url'], false);
333 if (!empty($profile) && empty($contacts[$profile['url']])) {
334 $data['cc'][] = $profile['url'];
335 $contacts[$profile['url']] = $profile['url'];
339 $receiver_list = Item::enumeratePermissions($item);
343 foreach ($terms as $term) {
344 if ($term['type'] != TERM_MENTION) {
347 $cid = Contact::getIdForURL($term['url'], $item['uid']);
348 if (!empty($cid) && in_array($cid, $receiver_list)) {
349 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
350 $data['to'][] = $contact['url'];
351 $contacts[$contact['url']] = $contact['url'];
355 foreach ($receiver_list as $receiver) {
356 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
357 if (empty($contacts[$contact['url']])) {
358 $data['cc'][] = $contact['url'];
359 $contacts[$contact['url']] = $contact['url'];
364 $parents = Item::select(['author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
365 while ($parent = Item::fetch($parents)) {
366 // Don't include data from future posts
367 if ($parent['id'] >= $item['id']) {
371 $profile = self::fetchprofile($parent['author-link'], false);
372 if (!empty($profile) && empty($contacts[$profile['url']])) {
373 $data['cc'][] = $profile['url'];
374 $contacts[$profile['url']] = $profile['url'];
377 if ($item['gravity'] != GRAVITY_PARENT) {
381 $profile = self::fetchprofile($parent['owner-link'], false);
382 if (!empty($profile) && empty($contacts[$profile['url']])) {
383 $data['cc'][] = $profile['url'];
384 $contacts[$profile['url']] = $profile['url'];
387 DBA::close($parents);
389 if (empty($data['to'])) {
390 $data['to'] = $data['cc'];
397 public static function fetchTargetInboxes($item, $uid)
399 $permissions = self::createPermissionBlockForItem($item);
400 if (empty($permissions)) {
406 if ($item['gravity'] == GRAVITY_ACTIVITY) {
407 $item_profile = ActivityPub::fetchprofile($item['author-link']);
409 $item_profile = ActivityPub::fetchprofile($item['owner-link']);
412 $elements = ['to', 'cc', 'bto', 'bcc'];
413 foreach ($elements as $element) {
414 if (empty($permissions[$element])) {
418 foreach ($permissions[$element] as $receiver) {
419 if ($receiver == $item_profile['followers']) {
420 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
421 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
422 while ($contact = DBA::fetch($contacts)) {
423 $contact = defaults($contact, 'batch', $contact['notify']);
424 $inboxes[$contact] = $contact;
426 DBA::close($contacts);
428 $profile = self::fetchprofile($receiver);
429 if (!empty($profile)) {
430 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
431 $inboxes[$target] = $target;
440 public static function getTypeOfItem($item)
442 if ($item['verb'] == ACTIVITY_POST) {
443 if ($item['created'] == $item['edited']) {
448 } elseif ($item['verb'] == ACTIVITY_LIKE) {
450 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
452 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
454 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
456 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
457 $type = 'TentativeAccept';
465 public static function createActivityFromItem($item_id, $object_mode = false)
467 $item = Item::selectFirst([], ['id' => $item_id]);
469 if (!DBA::isResult($item)) {
473 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
474 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
475 if (DBA::isResult($conversation)) {
476 $data = json_decode($conversation['source']);
482 $type = self::getTypeOfItem($item);
485 $data = ['@context' => self::CONTEXT];
487 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
489 } elseif ($item['deleted']) {
496 $data['id'] = $item['uri'] . '#' . $type;
497 $data['type'] = $type;
498 $data['actor'] = $item['author-link'];
500 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
502 if ($item["created"] != $item["edited"]) {
503 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
506 $data['context'] = self::createConversationURLFromItem($item);
508 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
510 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
511 $data['object'] = self::CreateNote($item);
512 } elseif ($data['type'] == 'Undo') {
513 $data['object'] = self::createActivityFromItem($item_id, true);
515 $data['object'] = $item['thr-parent'];
518 $owner = User::getOwnerDataById($item['uid']);
521 return LDSignature::sign($data, $owner);
527 public static function createObjectFromItemID($item_id)
529 $item = Item::selectFirst([], ['id' => $item_id]);
531 if (!DBA::isResult($item)) {
535 $data = ['@context' => self::CONTEXT];
536 $data = array_merge($data, self::CreateNote($item));
541 private static function createTagList($item)
545 $terms = Term::tagArrayFromItemId($item['id']);
546 foreach ($terms as $term) {
547 if ($term['type'] == TERM_MENTION) {
548 $contact = Contact::getDetailsByURL($term['url']);
549 if (!empty($contact['addr'])) {
550 $mention = '@' . $contact['addr'];
552 $mention = '@' . $term['url'];
555 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
561 private static function createConversationURLFromItem($item)
563 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
564 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
565 $conversation_uri = $conversation['conversation-uri'];
567 $conversation_uri = $item['parent-uri'];
569 return $conversation_uri;
572 private static function CreateNote($item)
574 if (!empty($item['title'])) {
580 if ($item['deleted']) {
585 $data['id'] = $item['uri'];
586 $data['type'] = $type;
588 if ($item['deleted']) {
592 $data['summary'] = null; // Ignore by now
594 if ($item['uri'] != $item['thr-parent']) {
595 $data['inReplyTo'] = $item['thr-parent'];
597 $data['inReplyTo'] = null;
600 $data['uuid'] = $item['guid'];
601 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
603 if ($item["created"] != $item["edited"]) {
604 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
607 $data['url'] = $item['plink'];
608 $data['attributedTo'] = $item['author-link'];
609 $data['actor'] = $item['author-link'];
610 $data['sensitive'] = false; // - Query NSFW
611 $data['conversation'] = $data['context'] = self::createConversationURLFromItem($item);
613 if (!empty($item['title'])) {
614 $data['name'] = BBCode::convert($item['title'], false, 7);
617 $data['content'] = BBCode::convert($item['body'], false, 7);
618 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
619 $data['attachment'] = []; // @ToDo
620 $data['tag'] = self::createTagList($item);
621 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
623 //$data['emoji'] = []; // Ignore by now
627 public static function transmitActivity($activity, $target, $uid)
629 $profile = self::fetchprofile($target);
631 $owner = User::getOwnerDataById($uid);
633 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
634 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
636 'actor' => $owner['url'],
637 'object' => $profile['url'],
638 'to' => $profile['url']];
640 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
642 $signed = LDSignature::sign($data, $owner);
643 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
646 public static function transmitContactAccept($target, $id, $uid)
648 $profile = self::fetchprofile($target);
650 $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' => ['id' => $id, 'type' => 'Follow',
656 'actor' => $profile['url'],
657 'object' => $owner['url']],
658 'to' => $profile['url']];
660 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
662 $signed = LDSignature::sign($data, $owner);
663 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
666 public static function transmitContactReject($target, $id, $uid)
668 $profile = self::fetchprofile($target);
670 $owner = User::getOwnerDataById($uid);
671 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
672 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
674 'actor' => $owner['url'],
675 'object' => ['id' => $id, 'type' => 'Follow',
676 'actor' => $profile['url'],
677 'object' => $owner['url']],
678 'to' => $profile['url']];
680 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
682 $signed = LDSignature::sign($data, $owner);
683 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
686 public static function transmitContactUndo($target, $uid)
688 $profile = self::fetchprofile($target);
690 $id = System::baseUrl() . '/activity/' . System::createGUID();
692 $owner = User::getOwnerDataById($uid);
693 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
696 'actor' => $owner['url'],
697 'object' => ['id' => $id, 'type' => 'Follow',
698 'actor' => $owner['url'],
699 'object' => $profile['url']],
700 'to' => $profile['url']];
702 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
704 $signed = LDSignature::sign($data, $owner);
705 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
709 * Fetches ActivityPub content from the given url
711 * @param string $url content url
714 public static function fetchContent($url)
716 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
717 if (!$ret['success'] || empty($ret['body'])) {
720 return json_decode($ret['body'], true);
724 * Resolves the profile url from the address by using webfinger
726 * @param string $addr profile address (user@domain.tld)
729 private static function addrToUrl($addr)
731 $addr_parts = explode('@', $addr);
732 if (count($addr_parts) != 2) {
736 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
738 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
739 if (!$ret['success'] || empty($ret['body'])) {
743 $data = json_decode($ret['body'], true);
745 if (empty($data['links'])) {
749 foreach ($data['links'] as $link) {
750 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
754 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
755 return $link['href'];
763 * Fetches a profile form a given url
765 * @param string $url profile url
766 * @param boolean $update true = always update, false = never update, null = update when not found
767 * @return array profile array
769 public static function fetchprofile($url, $update = null)
775 if (empty($update)) {
776 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
777 if (DBA::isResult($apcontact)) {
781 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
782 if (DBA::isResult($apcontact)) {
786 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
787 if (DBA::isResult($apcontact)) {
791 if (!is_null($update)) {
796 if (empty(parse_url($url, PHP_URL_SCHEME))) {
797 $url = self::addrToUrl($url);
803 $data = self::fetchContent($url);
805 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
810 $apcontact['url'] = $data['id'];
811 $apcontact['uuid'] = defaults($data, 'uuid', null);
812 $apcontact['type'] = defaults($data, 'type', null);
813 $apcontact['following'] = defaults($data, 'following', null);
814 $apcontact['followers'] = defaults($data, 'followers', null);
815 $apcontact['inbox'] = defaults($data, 'inbox', null);
816 $apcontact['outbox'] = defaults($data, 'outbox', null);
817 $apcontact['sharedinbox'] = JsonLD::fetchElement($data, 'endpoints', 'sharedInbox');
818 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
819 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
820 $apcontact['about'] = defaults($data, 'summary', '');
821 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon', 'url');
822 $apcontact['alias'] = JsonLD::fetchElement($data, 'url', 'href');
824 $parts = parse_url($apcontact['url']);
825 unset($parts['scheme']);
826 unset($parts['path']);
827 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
829 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data, 'publicKey', 'publicKeyPem'));
832 // manuallyApprovesFollowers
835 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
837 // Unhandled from Misskey
838 // sharedInbox, isCat
840 // Unhandled from Kroeg
841 // kroeg:blocks, updated
843 // Check if the address is resolvable
844 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
845 $parts = parse_url($apcontact['url']);
846 unset($parts['path']);
847 $apcontact['baseurl'] = Network::unparseURL($parts);
849 $apcontact['addr'] = null;
852 if ($apcontact['url'] == $apcontact['alias']) {
853 $apcontact['alias'] = null;
856 $apcontact['updated'] = DateTimeFormat::utcNow();
858 DBA::update('apcontact', $apcontact, ['url' => $url], true);
860 // Update some data in the contact table with various ways to catch them all
861 $contact_fields = ['name' => $apcontact['name'], 'about' => $apcontact['about']];
862 DBA::update('contact', $contact_fields, ['nurl' => normalise_link($url)]);
864 $contacts = DBA::select('contact', ['uid', 'id'], ['nurl' => normalise_link($url)]);
865 while ($contact = DBA::fetch($contacts)) {
866 Contact::updateAvatar($apcontact['photo'], $contact['uid'], $contact['id']);
868 DBA::close($contacts);
870 // Update the gcontact table
871 DBA::update('gcontact', $contact_fields, ['nurl' => normalise_link($url)]);
877 * Fetches a profile from the given url into an array that is compatible to Probe::uri
879 * @param string $url profile url
882 public static function probeProfile($url)
884 $apcontact = self::fetchprofile($url, true);
885 if (empty($apcontact)) {
889 $profile = ['network' => Protocol::ACTIVITYPUB];
890 $profile['nick'] = $apcontact['nick'];
891 $profile['name'] = $apcontact['name'];
892 $profile['guid'] = $apcontact['uuid'];
893 $profile['url'] = $apcontact['url'];
894 $profile['addr'] = $apcontact['addr'];
895 $profile['alias'] = $apcontact['alias'];
896 $profile['photo'] = $apcontact['photo'];
897 // $profile['community']
898 // $profile['keywords']
899 // $profile['location']
900 $profile['about'] = $apcontact['about'];
901 $profile['batch'] = $apcontact['sharedinbox'];
902 $profile['notify'] = $apcontact['inbox'];
903 $profile['poll'] = $apcontact['outbox'];
904 $profile['pubkey'] = $apcontact['pubkey'];
905 $profile['baseurl'] = $apcontact['baseurl'];
907 // Remove all "null" fields
908 foreach ($profile as $field => $content) {
909 if (is_null($content)) {
910 unset($profile[$field]);
917 public static function processInbox($body, $header, $uid)
919 $http_signer = HTTPSignature::getSigner($body, $header);
920 if (empty($http_signer)) {
921 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
924 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
927 $activity = json_decode($body, true);
929 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
930 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
932 if (empty($activity)) {
933 logger('Invalid body.', LOGGER_DEBUG);
937 if (LDSignature::isSigned($activity)) {
938 $ld_signer = LDSignature::getSigner($activity);
939 if (!empty($ld_signer && ($actor == $http_signer))) {
940 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
941 $trust_source = true;
942 } elseif (!empty($ld_signer)) {
943 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
944 $trust_source = true;
945 } elseif ($actor == $http_signer) {
946 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
947 $trust_source = true;
949 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
950 $trust_source = false;
952 } elseif ($actor == $http_signer) {
953 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
954 $trust_source = true;
956 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
957 $trust_source = false;
960 self::processActivity($activity, $body, $uid, $trust_source);
963 public static function fetchOutbox($url, $uid)
965 $data = self::fetchContent($url);
970 if (!empty($data['orderedItems'])) {
971 $items = $data['orderedItems'];
972 } elseif (!empty($data['first']['orderedItems'])) {
973 $items = $data['first']['orderedItems'];
974 } elseif (!empty($data['first'])) {
975 self::fetchOutbox($data['first'], $uid);
981 foreach ($items as $activity) {
982 self::processActivity($activity, '', $uid, true);
986 private static function prepareObjectData($activity, $uid, &$trust_source)
988 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
990 logger('Empty actor', LOGGER_DEBUG);
994 // Fetch all receivers from to, cc, bto and bcc
995 $receivers = self::getReceivers($activity, $actor);
997 // When it is a delivery to a personal inbox we add that user to the receivers
999 $owner = User::getOwnerDataById($uid);
1000 $additional = ['uid:' . $uid => $uid];
1001 $receivers = array_merge($receivers, $additional);
1004 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
1006 if (is_string($activity['object'])) {
1007 $object_url = $activity['object'];
1008 } elseif (!empty($activity['object']['id'])) {
1009 $object_url = $activity['object']['id'];
1011 logger('No object found', LOGGER_DEBUG);
1015 // Fetch the content only on activities where this matters
1016 if (in_array($activity['type'], ['Create', 'Announce'])) {
1017 $object_data = self::fetchObject($object_url, $activity['object'], $trust_source);
1018 if (empty($object_data)) {
1019 logger("Object data couldn't be processed", LOGGER_DEBUG);
1022 // We had been able to retrieve the object data - so we can trust the source
1023 $trust_source = true;
1024 } elseif ($activity['type'] == 'Update') {
1026 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1027 $object_data['object'] = $activity['object'];
1028 } elseif ($activity['type'] == 'Accept') {
1030 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1031 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'actor');
1032 } elseif ($activity['type'] == 'Undo') {
1034 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1035 if ($object_data['object_type'] == 'Follow') {
1036 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'object');
1038 $object_data['object'] = $activity['object'];
1040 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
1041 // Create a mostly empty array out of the activity data (instead of the object).
1042 // This way we later don't have to check for the existence of ech individual array element.
1043 $object_data = self::processCommonData($activity);
1044 $object_data['name'] = $activity['type'];
1045 $object_data['author'] = $activity['actor'];
1046 $object_data['object'] = $object_url;
1047 } elseif ($activity['type'] == 'Follow') {
1048 $object_data['id'] = $activity['id'];
1049 $object_data['object'] = $object_url;
1054 $object_data = self::addActivityFields($object_data, $activity);
1056 $object_data['type'] = $activity['type'];
1057 $object_data['owner'] = $actor;
1058 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
1060 return $object_data;
1063 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
1065 if (empty($activity['type'])) {
1066 logger('Empty type', LOGGER_DEBUG);
1070 if (empty($activity['object'])) {
1071 logger('Empty object', LOGGER_DEBUG);
1075 if (empty($activity['actor'])) {
1076 logger('Empty actor', LOGGER_DEBUG);
1082 // title, atomUri, context_id, statusnetConversationId
1085 // context, location, signature;
1087 logger('Processing activity: ' . $activity['type'], 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_url, $object = [], $trust_source = false)
1285 if (!$trust_source || is_string($object)) {
1286 $data = self::fetchContent($object_url);
1288 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1289 $data = $object_url;
1291 logger('Fetched content for ' . $object_url, LOGGER_DEBUG);
1294 logger('Using original object for url ' . $object_url, 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_url, LOGGER_DEBUG);
1305 $data = self::CreateNote($item);
1308 if (empty($data['type'])) {
1309 logger('Empty type', LOGGER_DEBUG);
1312 $type = $data['type'];
1313 logger('Type ' . $type, LOGGER_DEBUG);
1316 if (in_array($type, ['Note', 'Article', 'Video'])) {
1317 $common = self::processCommonData($data);
1322 return array_merge($common, self::processNote($data));
1324 return array_merge($common, self::processArticle($data));
1326 return array_merge($common, self::processVideo($data));
1329 if (empty($data['object'])) {
1332 return self::fetchObject($data['object']);
1339 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1344 private static function processCommonData(&$object)
1346 if (empty($object['id'])) {
1351 $object_data['type'] = $object['type'];
1352 $object_data['uri'] = $object['id'];
1354 if (!empty($object['inReplyTo'])) {
1355 $object_data['reply-to-uri'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1357 $object_data['reply-to-uri'] = $object_data['uri'];
1360 $object_data['published'] = defaults($object, 'published', null);
1361 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1363 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1364 $object_data['published'] = $object_data['updated'];
1367 $object_data['uuid'] = defaults($object, 'uuid', null);
1368 $object_data['owner'] = $object_data['author'] = JsonLD::fetchElement($object, 'attributedTo', 'id');
1369 $object_data['context'] = defaults($object, 'context', null);
1370 $object_data['conversation'] = defaults($object, 'conversation', null);
1371 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1372 $object_data['name'] = defaults($object, 'title', null);
1373 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1374 $object_data['summary'] = defaults($object, 'summary', null);
1375 $object_data['content'] = defaults($object, 'content', null);
1376 $object_data['source'] = defaults($object, 'source', null);
1377 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1378 $object_data['attachments'] = defaults($object, 'attachment', null);
1379 $object_data['tags'] = defaults($object, 'tag', null);
1380 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1381 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1382 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1385 // @context, type, actor, signature, mediaType, duration, replies, icon
1387 // Also missing: (Defined in the standard, but currently unused)
1388 // audience, preview, endTime, startTime, generator, image
1390 return $object_data;
1393 private static function processNote($object)
1398 // emoji, atomUri, inReplyToAtomUri
1401 // contentMap, announcement_count, announcements, context_id, likes, like_count
1402 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1404 return $object_data;
1407 private static function processArticle($object)
1411 return $object_data;
1414 private static function processVideo($object)
1419 // category, licence, language, commentsEnabled
1422 // views, waitTranscoding, state, support, subtitleLanguage
1423 // likes, dislikes, shares, comments
1425 return $object_data;
1428 private static function convertMentions($body)
1430 $URLSearchString = "^\[\]";
1431 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1436 private static function constructTagList($tags, $sensitive)
1443 foreach ($tags as $tag) {
1444 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1445 if (!empty($tag_text)) {
1449 if (empty($tag['href'])) {
1454 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1458 /// @todo add nsfw for $sensitive
1463 private static function constructAttachList($attachments, $item)
1465 if (empty($attachments)) {
1469 foreach ($attachments as $attach) {
1470 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1471 if ($filetype == 'image') {
1472 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1474 if (!empty($item["attach"])) {
1475 $item["attach"] .= ',';
1477 $item["attach"] = '';
1479 if (!isset($attach['length'])) {
1480 $attach['length'] = "0";
1482 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1489 private static function createItem($activity, $body)
1492 $item['verb'] = ACTIVITY_POST;
1493 $item['parent-uri'] = $activity['reply-to-uri'];
1495 if ($activity['reply-to-uri'] == $activity['uri']) {
1496 $item['gravity'] = GRAVITY_PARENT;
1497 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1499 $item['gravity'] = GRAVITY_COMMENT;
1500 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1503 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1504 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1505 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1508 self::postItem($activity, $item, $body);
1511 private static function likeItem($activity, $body)
1514 $item['verb'] = ACTIVITY_LIKE;
1515 $item['parent-uri'] = $activity['object'];
1516 $item['gravity'] = GRAVITY_ACTIVITY;
1517 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1519 self::postItem($activity, $item, $body);
1522 private static function dislikeItem($activity, $body)
1525 $item['verb'] = ACTIVITY_DISLIKE;
1526 $item['parent-uri'] = $activity['object'];
1527 $item['gravity'] = GRAVITY_ACTIVITY;
1528 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1530 self::postItem($activity, $item, $body);
1533 private static function postItem($activity, $item, $body)
1535 /// @todo What to do with $activity['context']?
1537 $item['network'] = Protocol::ACTIVITYPUB;
1538 $item['private'] = !in_array(0, $activity['receiver']);
1539 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1540 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1541 $item['uri'] = $activity['uri'];
1542 $item['created'] = $activity['published'];
1543 $item['edited'] = $activity['updated'];
1544 $item['guid'] = $activity['uuid'];
1545 $item['title'] = HTML::toBBCode($activity['name']);
1546 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1547 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1548 $item['location'] = $activity['location'];
1549 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1550 $item['app'] = $activity['service'];
1551 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1553 $item = self::constructAttachList($activity['attachments'], $item);
1555 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1556 if (!empty($source)) {
1557 $item['body'] = $source;
1560 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1561 $item['source'] = $body;
1562 $item['conversation-uri'] = $activity['conversation'];
1564 foreach ($activity['receiver'] as $receiver) {
1565 $item['uid'] = $receiver;
1566 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1568 if (($receiver != 0) && empty($item['contact-id'])) {
1569 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1572 $item_id = Item::insert($item);
1573 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1577 private static function fetchMissingActivity($url, $child)
1579 if (Config::get('system', 'ostatus_full_threads')) {
1583 $object = ActivityPub::fetchContent($url);
1584 if (empty($object)) {
1585 logger('Activity ' . $url . ' was not fetchable, aborting.');
1590 $activity['@context'] = $object['@context'];
1591 unset($object['@context']);
1592 $activity['id'] = $object['id'];
1593 $activity['to'] = defaults($object, 'to', []);
1594 $activity['cc'] = defaults($object, 'cc', []);
1595 $activity['actor'] = $child['author'];
1596 $activity['object'] = $object;
1597 $activity['published'] = $object['published'];
1598 $activity['type'] = 'Create';
1600 self::processActivity($activity);
1601 logger('Activity ' . $url . ' had been fetched and processed.');
1604 private static function getUserOfObject($object)
1606 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1607 if (!DBA::isResult($self)) {
1610 return $self['uid'];
1614 private static function followUser($activity)
1616 $uid = self::getUserOfObject($activity['object']);
1621 $owner = User::getOwnerDataById($uid);
1623 $cid = Contact::getIdForURL($activity['owner'], $uid);
1625 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1630 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1631 'author-link' => $activity['owner']];
1633 Contact::addRelationship($owner, $contact, $item);
1634 $cid = Contact::getIdForURL($activity['owner'], $uid);
1639 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1640 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1641 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1644 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1645 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1648 private static function updatePerson($activity)
1650 if (empty($activity['object']['id'])) {
1654 self::fetchprofile($activity['object']['id'], true);
1657 private static function acceptFollowUser($activity)
1659 $uid = self::getUserOfObject($activity['object']);
1664 $owner = User::getOwnerDataById($uid);
1666 $cid = Contact::getIdForURL($activity['owner'], $uid);
1668 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1672 $fields = ['pending' => false];
1674 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1675 if ($contact['rel'] == Contact::FOLLOWER) {
1676 $fields['rel'] = Contact::FRIEND;
1679 $condition = ['id' => $cid];
1680 DBA::update('contact', $fields, $condition);
1681 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1684 private static function undoActivity($activity)
1686 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
1687 if (empty($activity_url)) {
1691 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1692 if (empty($actor)) {
1696 $author_id = Contact::getIdForURL($actor);
1697 if (empty($author_id)) {
1701 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1704 private static function undoFollowUser($activity)
1706 $uid = self::getUserOfObject($activity['object']);
1711 $owner = User::getOwnerDataById($uid);
1713 $cid = Contact::getIdForURL($activity['owner'], $uid);
1715 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1719 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1720 if (!DBA::isResult($contact)) {
1724 Contact::removeFollower($owner, $contact);
1725 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);