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\APContact;
16 use Friendica\Model\Item;
17 use Friendica\Model\Profile;
18 use Friendica\Model\Term;
19 use Friendica\Model\User;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Crypto;
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Content\Text\HTML;
24 use Friendica\Util\JsonLD;
25 use Friendica\Util\LDSignature;
26 use Friendica\Core\Config;
29 * @brief ActivityPub Protocol class
30 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
31 * https://www.w3.org/TR/activitypub/
32 * https://www.w3.org/TR/activitystreams-core/
33 * https://www.w3.org/TR/activitystreams-vocabulary/
35 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
36 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
38 * Digest: https://tools.ietf.org/html/rfc5843
39 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
41 * Mastodon implementation of supported activities:
42 * https://github.com/tootsuite/mastodon/blob/master/app/lib/activitypub/activity.rb#L26
47 * - Update (Image, Video, Article, Note)
51 * Check what this is meant to do:
57 * - Undo Accept (Problem: This could invert a contact accept or an event accept)
69 * - Queueing unsucessful deliveries
70 * - Polling the outboxes for missing content?
71 * - Possibly using the LD-JSON parser
75 const PUBLIC_COLLECTION = 'https://www.w3.org/ns/activitystreams#Public';
76 const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
77 ['vcard' => 'http://www.w3.org/2006/vcard/ns#',
78 'diaspora' => 'https://diasporafoundation.org/ns/',
79 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
80 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag']];
81 const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application'];
82 const CONTENT_TYPES = ['Note', 'Article', 'Video', 'Image'];
83 const ACTIVITY_TYPES = ['Like', 'Dislike', 'Accept', 'Reject', 'TentativeAccept'];
85 * @brief Checks if the web request is done for the AP protocol
89 public static function isRequest()
91 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
92 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
96 * @brief collects the lost of followers of the given owner
98 * @param array $owner Owner array
99 * @param integer $page Page number
101 * @return array of owners
103 public static function getFollowers($owner, $page = null)
105 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
106 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
107 $count = DBA::count('contact', $condition);
109 $data = ['@context' => self::CONTEXT];
110 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
111 $data['type'] = 'OrderedCollection';
112 $data['totalItems'] = $count;
114 // When we hide our friends we will only show the pure number but don't allow more.
115 $profile = Profile::getByUID($owner['uid']);
116 if (!empty($profile['hide-friends'])) {
121 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
125 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
126 while ($contact = DBA::fetch($contacts)) {
127 $list[] = $contact['url'];
131 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
134 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
136 $data['orderedItems'] = $list;
143 * @brief Create list of following contacts
145 * @param array $owner Owner array
146 * @param integer $page Page numbe
148 * @return array of following contacts
150 public static function getFollowing($owner, $page = null)
152 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
153 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
154 $count = DBA::count('contact', $condition);
156 $data = ['@context' => self::CONTEXT];
157 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
158 $data['type'] = 'OrderedCollection';
159 $data['totalItems'] = $count;
161 // When we hide our friends we will only show the pure number but don't allow more.
162 $profile = Profile::getByUID($owner['uid']);
163 if (!empty($profile['hide-friends'])) {
168 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
172 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
173 while ($contact = DBA::fetch($contacts)) {
174 $list[] = $contact['url'];
178 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
181 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
183 $data['orderedItems'] = $list;
190 * @brief Public posts for the given owner
192 * @param array $owner Owner array
193 * @param integer $page Page numbe
195 * @return array of posts
197 public static function getOutbox($owner, $page = null)
199 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
201 $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
202 'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
203 'deleted' => false, 'visible' => true];
204 $count = DBA::count('item', $condition);
206 $data = ['@context' => self::CONTEXT];
207 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
208 $data['type'] = 'OrderedCollection';
209 $data['totalItems'] = $count;
212 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
216 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
218 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
219 while ($item = Item::fetch($items)) {
220 $object = self::createObjectFromItemID($item['id']);
221 unset($object['@context']);
226 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
229 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
231 $data['orderedItems'] = $list;
238 * Return the ActivityPub profile of the given user
240 * @param integer $uid User ID
241 * @return profile array
243 public static function profile($uid)
245 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
246 'account_removed' => false, 'verified' => true];
247 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
248 $user = DBA::selectFirst('user', $fields, $condition);
249 if (!DBA::isResult($user)) {
253 $fields = ['locality', 'region', 'country-name'];
254 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
255 if (!DBA::isResult($profile)) {
259 $fields = ['name', 'url', 'location', 'about', 'avatar'];
260 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
261 if (!DBA::isResult($contact)) {
265 $data = ['@context' => self::CONTEXT];
266 $data['id'] = $contact['url'];
267 $data['diaspora:guid'] = $user['guid'];
268 $data['type'] = self::ACCOUNT_TYPES[$user['account-type']];
269 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
270 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
271 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
272 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
273 $data['preferredUsername'] = $user['nickname'];
274 $data['name'] = $contact['name'];
275 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
276 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
277 $data['summary'] = $contact['about'];
278 $data['url'] = $contact['url'];
279 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
280 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
281 'owner' => $contact['url'],
282 'publicKeyPem' => $user['pubkey']];
283 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
284 $data['icon'] = ['type' => 'Image',
285 'url' => $contact['avatar']];
287 // tags: https://kitty.town/@inmysocks/100656097926961126.json
292 * @brief Returns an array with permissions of a given item array
296 * @return array with permissions
298 private static function fetchPermissionBlockFromConversation($item)
300 if (empty($item['thr-parent'])) {
304 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
305 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
306 if (!DBA::isResult($conversation)) {
310 $activity = json_decode($conversation['source'], true);
312 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
313 $profile = APContact::getByURL($actor);
315 $item_profile = APContact::getByURL($item['author-link']);
316 $exclude[] = $item['author-link'];
318 if ($item['gravity'] == GRAVITY_PARENT) {
319 $exclude[] = $item['owner-link'];
322 $permissions['to'][] = $actor;
324 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
325 if (empty($activity[$element])) {
328 if (is_string($activity[$element])) {
329 $activity[$element] = [$activity[$element]];
332 foreach ($activity[$element] as $receiver) {
333 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
334 $receiver = $item_profile['followers'];
336 if (!in_array($receiver, $exclude)) {
337 $permissions[$element][] = $receiver;
345 * @brief Creates an array of permissions from an item thread
349 * @return permission array
351 public static function createPermissionBlockForItem($item)
353 $data = ['to' => [], 'cc' => []];
355 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
357 $actor_profile = APContact::getByURL($item['author-link']);
359 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
361 $contacts[$item['author-link']] = $item['author-link'];
363 if (!$item['private']) {
364 $data['to'][] = self::PUBLIC_COLLECTION;
365 if (!empty($actor_profile['followers'])) {
366 $data['cc'][] = $actor_profile['followers'];
369 foreach ($terms as $term) {
370 $profile = APContact::getByURL($term['url'], false);
371 if (!empty($profile) && empty($contacts[$profile['url']])) {
372 $data['cc'][] = $profile['url'];
373 $contacts[$profile['url']] = $profile['url'];
377 $receiver_list = Item::enumeratePermissions($item);
381 foreach ($terms as $term) {
382 $cid = Contact::getIdForURL($term['url'], $item['uid']);
383 if (!empty($cid) && in_array($cid, $receiver_list)) {
384 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
385 $data['to'][] = $contact['url'];
386 $contacts[$contact['url']] = $contact['url'];
390 foreach ($receiver_list as $receiver) {
391 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
392 if (empty($contacts[$contact['url']])) {
393 $data['cc'][] = $contact['url'];
394 $contacts[$contact['url']] = $contact['url'];
399 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
400 while ($parent = Item::fetch($parents)) {
401 // Don't include data from future posts
402 if ($parent['id'] >= $item['id']) {
406 $profile = APContact::getByURL($parent['author-link'], false);
407 if (!empty($profile) && empty($contacts[$profile['url']])) {
408 $data['cc'][] = $profile['url'];
409 $contacts[$profile['url']] = $profile['url'];
412 if ($item['gravity'] != GRAVITY_PARENT) {
416 $profile = APContact::getByURL($parent['owner-link'], false);
417 if (!empty($profile) && empty($contacts[$profile['url']])) {
418 $data['cc'][] = $profile['url'];
419 $contacts[$profile['url']] = $profile['url'];
422 DBA::close($parents);
424 if (empty($data['to'])) {
425 $data['to'] = $data['cc'];
433 * @brief Fetches a list of inboxes of followers of a given user
435 * @param integer $uid User ID
437 * @return array of follower inboxes
439 public static function fetchTargetInboxesforUser($uid)
443 $condition = ['uid' => $uid, 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
446 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
449 $contacts = DBA::select('contact', ['notify', 'batch'], $condition);
450 while ($contact = DBA::fetch($contacts)) {
451 $contact = defaults($contact, 'batch', $contact['notify']);
452 $inboxes[$contact] = $contact;
454 DBA::close($contacts);
460 * @brief Fetches an array of inboxes for the given item and user
463 * @param integer $uid User ID
465 * @return array with inboxes
467 public static function fetchTargetInboxes($item, $uid)
469 $permissions = self::createPermissionBlockForItem($item);
470 if (empty($permissions)) {
476 if ($item['gravity'] == GRAVITY_ACTIVITY) {
477 $item_profile = APContact::getByURL($item['author-link']);
479 $item_profile = APContact::getByURL($item['owner-link']);
482 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
483 if (empty($permissions[$element])) {
487 foreach ($permissions[$element] as $receiver) {
488 if ($receiver == $item_profile['followers']) {
489 $inboxes = self::fetchTargetInboxesforUser($uid);
491 $profile = APContact::getByURL($receiver);
492 if (!empty($profile)) {
493 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
494 $inboxes[$target] = $target;
504 * @brief Returns the activity type of a given item
508 * @return activity type
510 public static function getTypeOfItem($item)
512 if ($item['verb'] == ACTIVITY_POST) {
513 if ($item['created'] == $item['edited']) {
518 } elseif ($item['verb'] == ACTIVITY_LIKE) {
520 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
522 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
524 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
526 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
527 $type = 'TentativeAccept';
536 * @brief Creates an activity array for a given item id
538 * @param integer $item_id
539 * @param boolean $object_mode Is the activity item is used inside another object?
541 * @return array of activity
543 public static function createActivityFromItem($item_id, $object_mode = false)
545 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
547 if (!DBA::isResult($item)) {
551 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
552 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
553 if (DBA::isResult($conversation)) {
554 $data = json_decode($conversation['source']);
560 $type = self::getTypeOfItem($item);
563 $data = ['@context' => self::CONTEXT];
565 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
567 } elseif ($item['deleted']) {
574 $data['id'] = $item['uri'] . '#' . $type;
575 $data['type'] = $type;
576 $data['actor'] = $item['author-link'];
578 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
580 if ($item["created"] != $item["edited"]) {
581 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
584 $data['context'] = self::fetchContextURLForItem($item);
586 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
588 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
589 $data['object'] = self::createNote($item);
590 } elseif ($data['type'] == 'Undo') {
591 $data['object'] = self::createActivityFromItem($item_id, true);
593 $data['object'] = $item['thr-parent'];
596 $owner = User::getOwnerDataById($item['uid']);
599 return LDSignature::sign($data, $owner);
606 * @brief Creates an object array for a given item id
608 * @param integer $item_id
610 * @return object array
612 public static function createObjectFromItemID($item_id)
614 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
616 if (!DBA::isResult($item)) {
620 $data = ['@context' => self::CONTEXT];
621 $data = array_merge($data, self::createNote($item));
627 * @brief Returns a tag array for a given item array
631 * @return array of tags
633 private static function createTagList($item)
637 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
638 foreach ($terms as $term) {
639 $contact = Contact::getDetailsByURL($term['url']);
640 if (!empty($contact['addr'])) {
641 $mention = '@' . $contact['addr'];
643 $mention = '@' . $term['url'];
646 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
652 * @brief Fetches the "context" value for a givem item array from the "conversation" table
656 * @return string with context url
658 private static function fetchContextURLForItem($item)
660 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
661 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
662 $context_uri = $conversation['conversation-href'];
663 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
664 $context_uri = $conversation['conversation-uri'];
666 $context_uri = str_replace('/object/', '/context/', $item['parent-uri']);
672 * @brief Creates a note/article object array
676 * @return object array
678 private static function createNote($item)
680 if (!empty($item['title'])) {
686 if ($item['deleted']) {
691 $data['id'] = $item['uri'];
692 $data['type'] = $type;
694 if ($item['deleted']) {
698 $data['summary'] = null; // Ignore by now
700 if ($item['uri'] != $item['thr-parent']) {
701 $data['inReplyTo'] = $item['thr-parent'];
703 $data['inReplyTo'] = null;
706 $data['diaspora:guid'] = $item['guid'];
707 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
709 if ($item["created"] != $item["edited"]) {
710 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
713 $data['url'] = $item['plink'];
714 $data['attributedTo'] = $item['author-link'];
715 $data['actor'] = $item['author-link'];
716 $data['sensitive'] = false; // - Query NSFW
717 $data['context'] = self::fetchContextURLForItem($item);
719 if (!empty($item['title'])) {
720 $data['name'] = BBCode::convert($item['title'], false, 7);
723 $data['content'] = BBCode::convert($item['body'], false, 7);
724 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
726 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
727 $data['diaspora:comment'] = $item['signed_text'];
730 $data['attachment'] = []; // @ToDo
731 $data['tag'] = self::createTagList($item);
732 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
738 * @brief Transmits a profile deletion to a given inbox
740 * @param integer $uid User ID
741 * @param string $inbox Target inbox
743 public static function transmitProfileDeletion($uid, $inbox)
745 $owner = User::getOwnerDataById($uid);
746 $profile = APContact::getByURL($owner['url']);
748 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
749 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
751 'actor' => $owner['url'],
752 'object' => self::profile($uid),
753 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
754 'to' => [self::PUBLIC_COLLECTION],
757 $signed = LDSignature::sign($data, $owner);
759 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
760 HTTPSignature::transmit($signed, $inbox, $uid);
764 * @brief Transmits a profile change to a given inbox
766 * @param integer $uid User ID
767 * @param string $inbox Target inbox
769 public static function transmitProfileUpdate($uid, $inbox)
771 $owner = User::getOwnerDataById($uid);
772 $profile = APContact::getByURL($owner['url']);
774 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
775 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
777 'actor' => $owner['url'],
778 'object' => self::profile($uid),
779 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
780 'to' => [$profile['followers']],
783 $signed = LDSignature::sign($data, $owner);
785 logger('Deliver profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
786 HTTPSignature::transmit($signed, $inbox, $uid);
790 * @brief Transmits a given activity to a target
792 * @param array $activity
793 * @param string $target Target profile
794 * @param integer $uid User ID
796 public static function transmitActivity($activity, $target, $uid)
798 $profile = APContact::getByURL($target);
800 $owner = User::getOwnerDataById($uid);
802 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
803 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
805 'actor' => $owner['url'],
806 'object' => $profile['url'],
807 'to' => $profile['url']];
809 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
811 $signed = LDSignature::sign($data, $owner);
812 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
816 * @brief Transmit a message that the contact request had been accepted
818 * @param string $target Target profile
820 * @param integer $uid User ID
822 public static function transmitContactAccept($target, $id, $uid)
824 $profile = APContact::getByURL($target);
826 $owner = User::getOwnerDataById($uid);
827 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
828 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
830 'actor' => $owner['url'],
831 'object' => ['id' => $id, 'type' => 'Follow',
832 'actor' => $profile['url'],
833 'object' => $owner['url']],
834 'to' => $profile['url']];
836 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
838 $signed = LDSignature::sign($data, $owner);
839 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
845 * @param string $target Target profile
847 * @param integer $uid User ID
849 public static function transmitContactReject($target, $id, $uid)
851 $profile = APContact::getByURL($target);
853 $owner = User::getOwnerDataById($uid);
854 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
855 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
857 'actor' => $owner['url'],
858 'object' => ['id' => $id, 'type' => 'Follow',
859 'actor' => $profile['url'],
860 'object' => $owner['url']],
861 'to' => $profile['url']];
863 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
865 $signed = LDSignature::sign($data, $owner);
866 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
872 * @param string $target Target profile
873 * @param integer $uid User ID
875 public static function transmitContactUndo($target, $uid)
877 $profile = APContact::getByURL($target);
879 $id = System::baseUrl() . '/activity/' . System::createGUID();
881 $owner = User::getOwnerDataById($uid);
882 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
885 'actor' => $owner['url'],
886 'object' => ['id' => $id, 'type' => 'Follow',
887 'actor' => $owner['url'],
888 'object' => $profile['url']],
889 'to' => $profile['url']];
891 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
893 $signed = LDSignature::sign($data, $owner);
894 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
898 * Fetches ActivityPub content from the given url
900 * @param string $url content url
903 public static function fetchContent($url)
905 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
906 if (!$ret['success'] || empty($ret['body'])) {
910 return json_decode($ret['body'], true);
914 * Fetches a profile from the given url into an array that is compatible to Probe::uri
916 * @param string $url profile url
919 public static function probeProfile($url)
921 $apcontact = APContact::getByURL($url, true);
922 if (empty($apcontact)) {
926 $profile = ['network' => Protocol::ACTIVITYPUB];
927 $profile['nick'] = $apcontact['nick'];
928 $profile['name'] = $apcontact['name'];
929 $profile['guid'] = $apcontact['uuid'];
930 $profile['url'] = $apcontact['url'];
931 $profile['addr'] = $apcontact['addr'];
932 $profile['alias'] = $apcontact['alias'];
933 $profile['photo'] = $apcontact['photo'];
934 // $profile['community']
935 // $profile['keywords']
936 // $profile['location']
937 $profile['about'] = $apcontact['about'];
938 $profile['batch'] = $apcontact['sharedinbox'];
939 $profile['notify'] = $apcontact['inbox'];
940 $profile['poll'] = $apcontact['outbox'];
941 $profile['pubkey'] = $apcontact['pubkey'];
942 $profile['baseurl'] = $apcontact['baseurl'];
944 // Remove all "null" fields
945 foreach ($profile as $field => $content) {
946 if (is_null($content)) {
947 unset($profile[$field]);
959 * @param integer $uid User ID
961 public static function processInbox($body, $header, $uid)
963 $http_signer = HTTPSignature::getSigner($body, $header);
964 if (empty($http_signer)) {
965 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
968 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
971 $activity = json_decode($body, true);
973 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
974 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
976 if (empty($activity)) {
977 logger('Invalid body.', LOGGER_DEBUG);
981 if (LDSignature::isSigned($activity)) {
982 $ld_signer = LDSignature::getSigner($activity);
983 if (empty($ld_signer)) {
984 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
986 if (!empty($ld_signer && ($actor == $http_signer))) {
987 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
988 $trust_source = true;
989 } elseif (!empty($ld_signer)) {
990 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
991 $trust_source = true;
992 } elseif ($actor == $http_signer) {
993 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
994 $trust_source = true;
996 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
997 $trust_source = false;
999 } elseif ($actor == $http_signer) {
1000 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
1001 $trust_source = true;
1003 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
1004 $trust_source = false;
1007 self::processActivity($activity, $body, $uid, $trust_source);
1014 * @param integer $uid User ID
1016 public static function fetchOutbox($url, $uid)
1018 $data = self::fetchContent($url);
1023 if (!empty($data['orderedItems'])) {
1024 $items = $data['orderedItems'];
1025 } elseif (!empty($data['first']['orderedItems'])) {
1026 $items = $data['first']['orderedItems'];
1027 } elseif (!empty($data['first'])) {
1028 self::fetchOutbox($data['first'], $uid);
1034 foreach ($items as $activity) {
1035 self::processActivity($activity, '', $uid, true);
1042 * @param array $activity
1043 * @param integer $uid User ID
1044 * @param $trust_source
1048 private static function prepareObjectData($activity, $uid, &$trust_source)
1050 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
1051 if (empty($actor)) {
1052 logger('Empty actor', LOGGER_DEBUG);
1056 // Fetch all receivers from to, cc, bto and bcc
1057 $receivers = self::getReceivers($activity, $actor);
1059 // When it is a delivery to a personal inbox we add that user to the receivers
1061 $owner = User::getOwnerDataById($uid);
1062 $additional = ['uid:' . $uid => $uid];
1063 $receivers = array_merge($receivers, $additional);
1066 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
1068 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
1069 if (empty($object_id)) {
1070 logger('No object found', LOGGER_DEBUG);
1074 // Fetch the content only on activities where this matters
1075 if (in_array($activity['type'], ['Create', 'Announce'])) {
1076 $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
1077 if (empty($object_data)) {
1078 logger("Object data couldn't be processed", LOGGER_DEBUG);
1081 // We had been able to retrieve the object data - so we can trust the source
1082 $trust_source = true;
1083 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
1084 // Create a mostly empty array out of the activity data (instead of the object).
1085 // This way we later don't have to check for the existence of ech individual array element.
1086 $object_data = self::processObject($activity);
1087 $object_data['name'] = $activity['type'];
1088 $object_data['author'] = $activity['actor'];
1089 $object_data['object'] = $object_id;
1090 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
1093 $object_data['id'] = $activity['id'];
1094 $object_data['object'] = $activity['object'];
1095 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1098 $object_data = self::addActivityFields($object_data, $activity);
1100 $object_data['type'] = $activity['type'];
1101 $object_data['owner'] = $actor;
1102 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
1104 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
1106 return $object_data;
1112 * @param array $activity
1114 * @param integer $uid User ID
1115 * @param $trust_source
1117 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
1119 if (empty($activity['type'])) {
1120 logger('Empty type', LOGGER_DEBUG);
1124 if (empty($activity['object'])) {
1125 logger('Empty object', LOGGER_DEBUG);
1129 if (empty($activity['actor'])) {
1130 logger('Empty actor', LOGGER_DEBUG);
1135 // $trust_source is called by reference and is set to true if the content was retrieved successfully
1136 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
1137 if (empty($object_data)) {
1138 logger('No object data found', LOGGER_DEBUG);
1142 if (!$trust_source) {
1143 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
1146 switch ($activity['type']) {
1149 self::createItem($object_data, $body);
1153 self::likeItem($object_data, $body);
1157 self::dislikeItem($object_data, $body);
1161 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
1163 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
1164 self::updatePerson($object_data, $body);
1169 if ($object_data['object_type'] == 'Tombstone') {
1170 self::deleteItem($object_data, $body);
1171 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
1172 self::deletePerson($object_data, $body);
1177 self::followUser($object_data);
1181 if ($object_data['object_type'] == 'Follow') {
1182 self::acceptFollowUser($object_data);
1187 if ($object_data['object_type'] == 'Follow') {
1188 self::rejectFollowUser($object_data);
1193 if ($object_data['object_type'] == 'Follow') {
1194 self::undoFollowUser($object_data);
1195 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1196 self::undoActivity($object_data);
1201 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
1209 * @param array $activity
1214 private static function getReceivers($activity, $actor)
1218 // When it is an answer, we inherite the receivers from the parent
1219 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1220 if (!empty($replyto)) {
1221 $parents = Item::select(['uid'], ['uri' => $replyto]);
1222 while ($parent = Item::fetch($parents)) {
1223 $receivers['uid:' . $parent['uid']] = $parent['uid'];
1227 if (!empty($actor)) {
1228 $profile = APContact::getByURL($actor);
1229 $followers = defaults($profile, 'followers', '');
1231 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
1233 logger('Empty actor', LOGGER_DEBUG);
1237 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
1238 if (empty($activity[$element])) {
1242 // The receiver can be an array or a string
1243 if (is_string($activity[$element])) {
1244 $activity[$element] = [$activity[$element]];
1247 foreach ($activity[$element] as $receiver) {
1248 if ($receiver == self::PUBLIC_COLLECTION) {
1249 $receivers['uid:0'] = 0;
1252 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
1253 // This will most likely catch all OStatus connections to Mastodon
1254 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
1255 , 'archive' => false, 'pending' => false];
1256 $contacts = DBA::select('contact', ['uid'], $condition);
1257 while ($contact = DBA::fetch($contacts)) {
1258 if ($contact['uid'] != 0) {
1259 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1262 DBA::close($contacts);
1265 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
1266 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1267 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
1268 $contacts = DBA::select('contact', ['uid'], $condition);
1269 while ($contact = DBA::fetch($contacts)) {
1270 if ($contact['uid'] != 0) {
1271 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1274 DBA::close($contacts);
1278 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1279 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1280 if (!DBA::isResult($contact)) {
1283 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1287 self::switchContacts($receivers, $actor);
1296 * @param integer $uid User ID
1299 private static function switchContact($cid, $uid, $url)
1301 $profile = ActivityPub::probeProfile($url);
1302 if (empty($profile)) {
1306 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
1308 $photo = $profile['photo'];
1309 unset($profile['photo']);
1310 unset($profile['baseurl']);
1312 $profile['nurl'] = normalise_link($profile['url']);
1313 DBA::update('contact', $profile, ['id' => $cid]);
1315 Contact::updateAvatar($photo, $uid, $cid);
1324 private static function switchContacts($receivers, $actor)
1326 if (empty($actor)) {
1330 foreach ($receivers as $receiver) {
1331 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
1332 if (DBA::isResult($contact)) {
1333 self::switchContact($contact['id'], $receiver, $actor);
1336 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
1337 if (DBA::isResult($contact)) {
1338 self::switchContact($contact['id'], $receiver, $actor);
1346 * @param $object_data
1347 * @param array $activity
1351 private static function addActivityFields($object_data, $activity)
1353 if (!empty($activity['published']) && empty($object_data['published'])) {
1354 $object_data['published'] = $activity['published'];
1357 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1358 $object_data['updated'] = $activity['updated'];
1361 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1362 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1365 if (!empty($activity['instrument'])) {
1366 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1368 return $object_data;
1376 * @param $trust_source
1380 private static function fetchObject($object_id, $object = [], $trust_source = false)
1382 if (!$trust_source || is_string($object)) {
1383 $data = self::fetchContent($object_id);
1385 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
1388 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
1391 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
1395 if (is_string($data)) {
1396 $item = Item::selectFirst([], ['uri' => $data]);
1397 if (!DBA::isResult($item)) {
1398 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1401 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
1402 $data = self::createNote($item);
1405 if (empty($data['type'])) {
1406 logger('Empty type', LOGGER_DEBUG);
1410 if (in_array($data['type'], self::CONTENT_TYPES)) {
1411 return self::processObject($data);
1414 if ($data['type'] == 'Announce') {
1415 if (empty($data['object'])) {
1418 return self::fetchObject($data['object']);
1421 logger('Unhandled object type: ' . $data['type'], LOGGER_DEBUG);
1431 private static function processObject($object)
1433 if (empty($object['id'])) {
1438 $object_data['object_type'] = $object['type'];
1439 $object_data['id'] = $object['id'];
1441 if (!empty($object['inReplyTo'])) {
1442 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1444 $object_data['reply-to-id'] = $object_data['id'];
1447 $object_data['published'] = defaults($object, 'published', null);
1448 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1450 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1451 $object_data['published'] = $object_data['updated'];
1454 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
1455 if (empty($actor)) {
1456 $actor = defaults($object, 'actor', null);
1459 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
1460 $object_data['owner'] = $object_data['author'] = $actor;
1461 $object_data['context'] = defaults($object, 'context', null);
1462 $object_data['conversation'] = defaults($object, 'conversation', null);
1463 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1464 $object_data['name'] = defaults($object, 'title', null);
1465 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1466 $object_data['summary'] = defaults($object, 'summary', null);
1467 $object_data['content'] = defaults($object, 'content', null);
1468 $object_data['source'] = defaults($object, 'source', null);
1469 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1470 $object_data['attachments'] = defaults($object, 'attachment', null);
1471 $object_data['tags'] = defaults($object, 'tag', null);
1472 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1473 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1474 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1476 // Common object data:
1479 // @context, type, actor, signature, mediaType, duration, replies, icon
1481 // Also missing: (Defined in the standard, but currently unused)
1482 // audience, preview, endTime, startTime, generator, image
1487 // contentMap, announcement_count, announcements, context_id, likes, like_count
1488 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1493 // category, licence, language, commentsEnabled
1496 // views, waitTranscoding, state, support, subtitleLanguage
1497 // likes, dislikes, shares, comments
1499 return $object_data;
1503 * @brief Converts mentions from Pleroma into the Friendica format
1505 * @param string $body
1507 * @return converted body
1509 private static function convertMentions($body)
1511 $URLSearchString = "^\[\]";
1512 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1518 * @brief Constructs a string with tags for a given tag array
1520 * @param array $tags
1521 * @param boolean $sensitive
1523 * @return string with tags
1525 private static function constructTagList($tags, $sensitive)
1532 foreach ($tags as $tag) {
1533 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1534 if (!empty($tag_text)) {
1538 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1542 /// @todo add nsfw for $sensitive
1550 * @param $attachments
1551 * @param array $item
1553 * @return item array
1555 private static function constructAttachList($attachments, $item)
1557 if (empty($attachments)) {
1561 foreach ($attachments as $attach) {
1562 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1563 if ($filetype == 'image') {
1564 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1566 if (!empty($item["attach"])) {
1567 $item["attach"] .= ',';
1569 $item["attach"] = '';
1571 if (!isset($attach['length'])) {
1572 $attach['length'] = "0";
1574 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1584 * @param array $activity
1587 private static function createItem($activity, $body)
1590 $item['verb'] = ACTIVITY_POST;
1591 $item['parent-uri'] = $activity['reply-to-id'];
1593 if ($activity['reply-to-id'] == $activity['id']) {
1594 $item['gravity'] = GRAVITY_PARENT;
1595 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1597 $item['gravity'] = GRAVITY_COMMENT;
1598 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1601 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
1602 logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
1603 self::fetchMissingActivity($activity['reply-to-id'], $activity);
1606 self::postItem($activity, $item, $body);
1612 * @param array $activity
1615 private static function likeItem($activity, $body)
1618 $item['verb'] = ACTIVITY_LIKE;
1619 $item['parent-uri'] = $activity['object'];
1620 $item['gravity'] = GRAVITY_ACTIVITY;
1621 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1623 self::postItem($activity, $item, $body);
1627 * @brief Delete items
1629 * @param array $activity
1632 private static function deleteItem($activity)
1634 $owner = Contact::getIdForURL($activity['owner']);
1635 $object = JsonLD::fetchElement($activity, 'object', 'id');
1636 logger('Deleting item ' . $object . ' from ' . $owner, LOGGER_DEBUG);
1637 Item::delete(['uri' => $object, 'owner-id' => $owner]);
1643 * @param array $activity
1646 private static function dislikeItem($activity, $body)
1649 $item['verb'] = ACTIVITY_DISLIKE;
1650 $item['parent-uri'] = $activity['object'];
1651 $item['gravity'] = GRAVITY_ACTIVITY;
1652 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1654 self::postItem($activity, $item, $body);
1660 * @param array $activity
1661 * @param array $item
1664 private static function postItem($activity, $item, $body)
1666 /// @todo What to do with $activity['context']?
1668 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
1669 logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
1673 $item['network'] = Protocol::ACTIVITYPUB;
1674 $item['private'] = !in_array(0, $activity['receiver']);
1675 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1676 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1677 $item['uri'] = $activity['id'];
1678 $item['created'] = $activity['published'];
1679 $item['edited'] = $activity['updated'];
1680 $item['guid'] = $activity['diaspora:guid'];
1681 $item['title'] = HTML::toBBCode($activity['name']);
1682 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1683 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1684 $item['location'] = $activity['location'];
1685 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1686 $item['app'] = $activity['service'];
1687 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1689 $item = self::constructAttachList($activity['attachments'], $item);
1691 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1692 if (!empty($source)) {
1693 $item['body'] = $source;
1696 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1697 $item['source'] = $body;
1698 $item['conversation-href'] = $activity['context'];
1699 $item['conversation-uri'] = $activity['conversation'];
1701 foreach ($activity['receiver'] as $receiver) {
1702 $item['uid'] = $receiver;
1703 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1705 if (($receiver != 0) && empty($item['contact-id'])) {
1706 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1709 $item_id = Item::insert($item);
1710 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1720 private static function fetchMissingActivity($url, $child)
1722 if (Config::get('system', 'ostatus_full_threads')) {
1726 $object = ActivityPub::fetchContent($url);
1727 if (empty($object)) {
1728 logger('Activity ' . $url . ' was not fetchable, aborting.');
1733 $activity['@context'] = $object['@context'];
1734 unset($object['@context']);
1735 $activity['id'] = $object['id'];
1736 $activity['to'] = defaults($object, 'to', []);
1737 $activity['cc'] = defaults($object, 'cc', []);
1738 $activity['actor'] = $child['author'];
1739 $activity['object'] = $object;
1740 $activity['published'] = $object['published'];
1741 $activity['type'] = 'Create';
1743 self::processActivity($activity);
1744 logger('Activity ' . $url . ' had been fetched and processed.');
1748 * @brief perform a "follow" request
1750 * @param array $activity
1752 private static function followUser($activity)
1754 $actor = JsonLD::fetchElement($activity, 'object', 'id');
1755 $uid = User::getIdForURL($actor);
1760 $owner = User::getOwnerDataById($uid);
1762 $cid = Contact::getIdForURL($activity['owner'], $uid);
1764 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1769 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1770 'author-link' => $activity['owner']];
1772 Contact::addRelationship($owner, $contact, $item);
1773 $cid = Contact::getIdForURL($activity['owner'], $uid);
1778 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1779 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1780 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1783 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1784 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1788 * @brief Update the given profile
1790 * @param array $activity
1792 private static function updatePerson($activity)
1794 if (empty($activity['object']['id'])) {
1798 logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
1799 APContact::getByURL($activity['object']['id'], true);
1803 * @brief Delete the given profile
1805 * @param array $activity
1807 private static function deletePerson($activity)
1809 if (empty($activity['object']['id']) || empty($activity['object']['actor'])) {
1810 logger('Empty object id or actor.', LOGGER_DEBUG);
1814 if ($activity['object']['id'] != $activity['object']['actor']) {
1815 logger('Object id does not match actor.', LOGGER_DEBUG);
1819 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object']['id'])]);
1820 while ($contact = DBA::fetch($contacts)) {
1821 Contact::remove($contact["id"]);
1823 DBA::close($contacts);
1825 logger('Deleted contact ' . $activity['object']['id'], LOGGER_DEBUG);
1829 * @brief Accept a follow request
1831 * @param array $activity
1833 private static function acceptFollowUser($activity)
1835 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1836 $uid = User::getIdForURL($actor);
1841 $owner = User::getOwnerDataById($uid);
1843 $cid = Contact::getIdForURL($activity['owner'], $uid);
1845 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1849 $fields = ['pending' => false];
1851 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1852 if ($contact['rel'] == Contact::FOLLOWER) {
1853 $fields['rel'] = Contact::FRIEND;
1856 $condition = ['id' => $cid];
1857 DBA::update('contact', $fields, $condition);
1858 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1862 * @brief Reject a follow request
1864 * @param array $activity
1866 private static function rejectFollowUser($activity)
1868 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1869 $uid = User::getIdForURL($actor);
1874 $owner = User::getOwnerDataById($uid);
1876 $cid = Contact::getIdForURL($activity['owner'], $uid);
1878 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1882 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
1883 Contact::remove($cid);
1884 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
1886 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
1891 * @brief Undo activity like "like" or "dislike"
1893 * @param array $activity
1895 private static function undoActivity($activity)
1897 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
1898 if (empty($activity_url)) {
1902 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1903 if (empty($actor)) {
1907 $author_id = Contact::getIdForURL($actor);
1908 if (empty($author_id)) {
1912 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1916 * @brief Activity to remove a follower
1918 * @param array $activity
1920 private static function undoFollowUser($activity)
1922 $object = JsonLD::fetchElement($activity, 'object', 'object');
1923 $uid = User::getIdForURL($object);
1928 $owner = User::getOwnerDataById($uid);
1930 $cid = Contact::getIdForURL($activity['owner'], $uid);
1932 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1936 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1937 if (!DBA::isResult($contact)) {
1941 Contact::removeFollower($owner, $contact);
1942 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);