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)
60 * - Delete (Application, Group, Organization, Person, Service)
70 * - Queueing unsucessful deliveries
71 * - Polling the outboxes for missing content?
72 * - Possibly using the LD-JSON parser
76 const PUBLIC_COLLECTION = 'https://www.w3.org/ns/activitystreams#Public';
77 const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
78 ['vcard' => 'http://www.w3.org/2006/vcard/ns#',
79 'diaspora' => 'https://diasporafoundation.org/ns/',
80 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
81 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag']];
82 const ACCOUNT_TYPES = ['Person', 'Organization', 'Service', 'Group', 'Application'];
83 const CONTENT_TYPES = ['Note', 'Article', 'Video', 'Image'];
84 const ACTIVITY_TYPES = ['Like', 'Dislike', 'Accept', 'Reject', 'TentativeAccept'];
86 * @brief Checks if the web request is done for the AP protocol
90 public static function isRequest()
92 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
93 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
97 * @brief collects the lost of followers of the given owner
99 * @param array $owner Owner array
100 * @param integer $page Page number
102 * @return array of owners
104 public static function getFollowers($owner, $page = null)
106 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
107 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
108 $count = DBA::count('contact', $condition);
110 $data = ['@context' => self::CONTEXT];
111 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
112 $data['type'] = 'OrderedCollection';
113 $data['totalItems'] = $count;
115 // When we hide our friends we will only show the pure number but don't allow more.
116 $profile = Profile::getByUID($owner['uid']);
117 if (!empty($profile['hide-friends'])) {
122 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
126 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
127 while ($contact = DBA::fetch($contacts)) {
128 $list[] = $contact['url'];
132 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
135 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
137 $data['orderedItems'] = $list;
144 * @brief Create list of following contacts
146 * @param array $owner Owner array
147 * @param integer $page Page numbe
149 * @return array of following contacts
151 public static function getFollowing($owner, $page = null)
153 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
154 'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
155 $count = DBA::count('contact', $condition);
157 $data = ['@context' => self::CONTEXT];
158 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
159 $data['type'] = 'OrderedCollection';
160 $data['totalItems'] = $count;
162 // When we hide our friends we will only show the pure number but don't allow more.
163 $profile = Profile::getByUID($owner['uid']);
164 if (!empty($profile['hide-friends'])) {
169 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
173 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
174 while ($contact = DBA::fetch($contacts)) {
175 $list[] = $contact['url'];
179 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
182 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
184 $data['orderedItems'] = $list;
191 * @brief Public posts for the given owner
193 * @param array $owner Owner array
194 * @param integer $page Page numbe
196 * @return array of posts
198 public static function getOutbox($owner, $page = null)
200 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
202 $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
203 'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
204 'deleted' => false, 'visible' => true];
205 $count = DBA::count('item', $condition);
207 $data = ['@context' => self::CONTEXT];
208 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
209 $data['type'] = 'OrderedCollection';
210 $data['totalItems'] = $count;
213 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
217 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
219 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
220 while ($item = Item::fetch($items)) {
221 $object = self::createObjectFromItemID($item['id']);
222 unset($object['@context']);
227 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
230 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
232 $data['orderedItems'] = $list;
239 * Return the ActivityPub profile of the given user
241 * @param integer $uid User ID
242 * @return profile array
244 public static function profile($uid)
246 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
247 'account_removed' => false, 'verified' => true];
248 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
249 $user = DBA::selectFirst('user', $fields, $condition);
250 if (!DBA::isResult($user)) {
254 $fields = ['locality', 'region', 'country-name'];
255 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
256 if (!DBA::isResult($profile)) {
260 $fields = ['name', 'url', 'location', 'about', 'avatar'];
261 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
262 if (!DBA::isResult($contact)) {
266 $data = ['@context' => self::CONTEXT];
267 $data['id'] = $contact['url'];
268 $data['diaspora:guid'] = $user['guid'];
269 $data['type'] = self::ACCOUNT_TYPES[$user['account-type']];
270 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
271 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
272 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
273 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
274 $data['preferredUsername'] = $user['nickname'];
275 $data['name'] = $contact['name'];
276 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
277 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
278 $data['summary'] = $contact['about'];
279 $data['url'] = $contact['url'];
280 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
281 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
282 'owner' => $contact['url'],
283 'publicKeyPem' => $user['pubkey']];
284 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
285 $data['icon'] = ['type' => 'Image',
286 'url' => $contact['avatar']];
288 // tags: https://kitty.town/@inmysocks/100656097926961126.json
293 * @brief Returns an array with permissions of a given item array
297 * @return array with permissions
299 private static function fetchPermissionBlockFromConversation($item)
301 if (empty($item['thr-parent'])) {
305 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
306 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
307 if (!DBA::isResult($conversation)) {
311 $activity = json_decode($conversation['source'], true);
313 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
314 $profile = APContact::getByURL($actor);
316 $item_profile = APContact::getByURL($item['author-link']);
317 $exclude[] = $item['author-link'];
319 if ($item['gravity'] == GRAVITY_PARENT) {
320 $exclude[] = $item['owner-link'];
323 $permissions['to'][] = $actor;
325 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
326 if (empty($activity[$element])) {
329 if (is_string($activity[$element])) {
330 $activity[$element] = [$activity[$element]];
333 foreach ($activity[$element] as $receiver) {
334 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
335 $receiver = $item_profile['followers'];
337 if (!in_array($receiver, $exclude)) {
338 $permissions[$element][] = $receiver;
346 * @brief Creates an array of permissions from an item thread
350 * @return permission array
352 public static function createPermissionBlockForItem($item)
354 $data = ['to' => [], 'cc' => []];
356 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
358 $actor_profile = APContact::getByURL($item['author-link']);
360 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
362 $contacts[$item['author-link']] = $item['author-link'];
364 if (!$item['private']) {
365 $data['to'][] = self::PUBLIC_COLLECTION;
366 if (!empty($actor_profile['followers'])) {
367 $data['cc'][] = $actor_profile['followers'];
370 foreach ($terms as $term) {
371 $profile = APContact::getByURL($term['url'], false);
372 if (!empty($profile) && empty($contacts[$profile['url']])) {
373 $data['cc'][] = $profile['url'];
374 $contacts[$profile['url']] = $profile['url'];
378 $receiver_list = Item::enumeratePermissions($item);
382 foreach ($terms as $term) {
383 $cid = Contact::getIdForURL($term['url'], $item['uid']);
384 if (!empty($cid) && in_array($cid, $receiver_list)) {
385 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
386 $data['to'][] = $contact['url'];
387 $contacts[$contact['url']] = $contact['url'];
391 foreach ($receiver_list as $receiver) {
392 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
393 if (empty($contacts[$contact['url']])) {
394 $data['cc'][] = $contact['url'];
395 $contacts[$contact['url']] = $contact['url'];
400 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
401 while ($parent = Item::fetch($parents)) {
402 // Don't include data from future posts
403 if ($parent['id'] >= $item['id']) {
407 $profile = APContact::getByURL($parent['author-link'], false);
408 if (!empty($profile) && empty($contacts[$profile['url']])) {
409 $data['cc'][] = $profile['url'];
410 $contacts[$profile['url']] = $profile['url'];
413 if ($item['gravity'] != GRAVITY_PARENT) {
417 $profile = APContact::getByURL($parent['owner-link'], false);
418 if (!empty($profile) && empty($contacts[$profile['url']])) {
419 $data['cc'][] = $profile['url'];
420 $contacts[$profile['url']] = $profile['url'];
423 DBA::close($parents);
425 if (empty($data['to'])) {
426 $data['to'] = $data['cc'];
434 * @brief Fetches a list of inboxes of followers of a given user
436 * @param integer $uid User ID
438 * @return array of follower inboxes
440 public static function fetchTargetInboxesforUser($uid)
444 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
445 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB,
446 'archive' => false, 'pending' => false]);
447 while ($contact = DBA::fetch($contacts)) {
448 $contact = defaults($contact, 'batch', $contact['notify']);
449 $inboxes[$contact] = $contact;
451 DBA::close($contacts);
457 * @brief Fetches an array of inboxes for the given item and user
460 * @param integer $uid User ID
462 * @return array with inboxes
464 public static function fetchTargetInboxes($item, $uid)
466 $permissions = self::createPermissionBlockForItem($item);
467 if (empty($permissions)) {
473 if ($item['gravity'] == GRAVITY_ACTIVITY) {
474 $item_profile = APContact::getByURL($item['author-link']);
476 $item_profile = APContact::getByURL($item['owner-link']);
479 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
480 if (empty($permissions[$element])) {
484 foreach ($permissions[$element] as $receiver) {
485 if ($receiver == $item_profile['followers']) {
486 $inboxes = self::fetchTargetInboxesforUser($uid);
488 $profile = APContact::getByURL($receiver);
489 if (!empty($profile)) {
490 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
491 $inboxes[$target] = $target;
501 * @brief Returns the activity type of a given item
505 * @return activity type
507 public static function getTypeOfItem($item)
509 if ($item['verb'] == ACTIVITY_POST) {
510 if ($item['created'] == $item['edited']) {
515 } elseif ($item['verb'] == ACTIVITY_LIKE) {
517 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
519 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
521 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
523 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
524 $type = 'TentativeAccept';
533 * @brief Creates an activity array for a given item id
535 * @param integer $item_id
536 * @param boolean $object_mode Is the activity item is used inside another object?
538 * @return array of activity
540 public static function createActivityFromItem($item_id, $object_mode = false)
542 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
544 if (!DBA::isResult($item)) {
548 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
549 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
550 if (DBA::isResult($conversation)) {
551 $data = json_decode($conversation['source']);
557 $type = self::getTypeOfItem($item);
560 $data = ['@context' => self::CONTEXT];
562 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
564 } elseif ($item['deleted']) {
571 $data['id'] = $item['uri'] . '#' . $type;
572 $data['type'] = $type;
573 $data['actor'] = $item['author-link'];
575 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
577 if ($item["created"] != $item["edited"]) {
578 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
581 $data['context'] = self::fetchContextURLForItem($item);
583 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
585 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
586 $data['object'] = self::createNote($item);
587 } elseif ($data['type'] == 'Undo') {
588 $data['object'] = self::createActivityFromItem($item_id, true);
590 $data['object'] = $item['thr-parent'];
593 $owner = User::getOwnerDataById($item['uid']);
596 return LDSignature::sign($data, $owner);
603 * @brief Creates an object array for a given item id
605 * @param integer $item_id
607 * @return object array
609 public static function createObjectFromItemID($item_id)
611 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
613 if (!DBA::isResult($item)) {
617 $data = ['@context' => self::CONTEXT];
618 $data = array_merge($data, self::createNote($item));
624 * @brief Returns a tag array for a given item array
628 * @return array of tags
630 private static function createTagList($item)
634 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
635 foreach ($terms as $term) {
636 $contact = Contact::getDetailsByURL($term['url']);
637 if (!empty($contact['addr'])) {
638 $mention = '@' . $contact['addr'];
640 $mention = '@' . $term['url'];
643 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
649 * @brief Fetches the "context" value for a givem item array from the "conversation" table
653 * @return string with context url
655 private static function fetchContextURLForItem($item)
657 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
658 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
659 $context_uri = $conversation['conversation-href'];
660 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
661 $context_uri = $conversation['conversation-uri'];
663 $context_uri = str_replace('/object/', '/context/', $item['parent-uri']);
669 * @brief Creates a note/article object array
673 * @return object array
675 private static function createNote($item)
677 if (!empty($item['title'])) {
683 if ($item['deleted']) {
688 $data['id'] = $item['uri'];
689 $data['type'] = $type;
691 if ($item['deleted']) {
695 $data['summary'] = null; // Ignore by now
697 if ($item['uri'] != $item['thr-parent']) {
698 $data['inReplyTo'] = $item['thr-parent'];
700 $data['inReplyTo'] = null;
703 $data['diaspora:guid'] = $item['guid'];
704 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
706 if ($item["created"] != $item["edited"]) {
707 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
710 $data['url'] = $item['plink'];
711 $data['attributedTo'] = $item['author-link'];
712 $data['actor'] = $item['author-link'];
713 $data['sensitive'] = false; // - Query NSFW
714 $data['context'] = self::fetchContextURLForItem($item);
716 if (!empty($item['title'])) {
717 $data['name'] = BBCode::convert($item['title'], false, 7);
720 $data['content'] = BBCode::convert($item['body'], false, 7);
721 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
723 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
724 $data['diaspora:comment'] = $item['signed_text'];
727 $data['attachment'] = []; // @ToDo
728 $data['tag'] = self::createTagList($item);
729 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
735 * @brief Transmits a profile change to a given inbox
737 * @param integer $uid User ID
738 * @param string $inbox Target inbox
740 public static function transmitProfileUpdate($uid, $inbox)
742 $owner = User::getOwnerDataById($uid);
743 $profile = APContact::getByURL($owner['url']);
745 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
746 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
748 'actor' => $owner['url'],
749 'object' => self::profile($uid),
750 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
751 'to' => [$profile['followers']],
754 $signed = LDSignature::sign($data, $owner);
756 logger('Deliver profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
757 HTTPSignature::transmit($signed, $inbox, $uid);
761 * @brief Transmits a given activity to a target
763 * @param array $activity
764 * @param string $target Target profile
765 * @param integer $uid User ID
767 public static function transmitActivity($activity, $target, $uid)
769 $profile = APContact::getByURL($target);
771 $owner = User::getOwnerDataById($uid);
773 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
774 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
776 'actor' => $owner['url'],
777 'object' => $profile['url'],
778 'to' => $profile['url']];
780 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
782 $signed = LDSignature::sign($data, $owner);
783 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
787 * @brief Transmit a message that the contact request had been accepted
789 * @param string $target Target profile
791 * @param integer $uid User ID
793 public static function transmitContactAccept($target, $id, $uid)
795 $profile = APContact::getByURL($target);
797 $owner = User::getOwnerDataById($uid);
798 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
799 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
801 'actor' => $owner['url'],
802 'object' => ['id' => $id, 'type' => 'Follow',
803 'actor' => $profile['url'],
804 'object' => $owner['url']],
805 'to' => $profile['url']];
807 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
809 $signed = LDSignature::sign($data, $owner);
810 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
816 * @param string $target Target profile
818 * @param integer $uid User ID
820 public static function transmitContactReject($target, $id, $uid)
822 $profile = APContact::getByURL($target);
824 $owner = User::getOwnerDataById($uid);
825 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
826 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
828 'actor' => $owner['url'],
829 'object' => ['id' => $id, 'type' => 'Follow',
830 'actor' => $profile['url'],
831 'object' => $owner['url']],
832 'to' => $profile['url']];
834 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
836 $signed = LDSignature::sign($data, $owner);
837 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
843 * @param string $target Target profile
844 * @param integer $uid User ID
846 public static function transmitContactUndo($target, $uid)
848 $profile = APContact::getByURL($target);
850 $id = System::baseUrl() . '/activity/' . System::createGUID();
852 $owner = User::getOwnerDataById($uid);
853 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
856 'actor' => $owner['url'],
857 'object' => ['id' => $id, 'type' => 'Follow',
858 'actor' => $owner['url'],
859 'object' => $profile['url']],
860 'to' => $profile['url']];
862 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
864 $signed = LDSignature::sign($data, $owner);
865 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
869 * Fetches ActivityPub content from the given url
871 * @param string $url content url
874 public static function fetchContent($url)
876 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
877 if (!$ret['success'] || empty($ret['body'])) {
881 return json_decode($ret['body'], true);
885 * Fetches a profile from the given url into an array that is compatible to Probe::uri
887 * @param string $url profile url
890 public static function probeProfile($url)
892 $apcontact = APContact::getByURL($url, true);
893 if (empty($apcontact)) {
897 $profile = ['network' => Protocol::ACTIVITYPUB];
898 $profile['nick'] = $apcontact['nick'];
899 $profile['name'] = $apcontact['name'];
900 $profile['guid'] = $apcontact['uuid'];
901 $profile['url'] = $apcontact['url'];
902 $profile['addr'] = $apcontact['addr'];
903 $profile['alias'] = $apcontact['alias'];
904 $profile['photo'] = $apcontact['photo'];
905 // $profile['community']
906 // $profile['keywords']
907 // $profile['location']
908 $profile['about'] = $apcontact['about'];
909 $profile['batch'] = $apcontact['sharedinbox'];
910 $profile['notify'] = $apcontact['inbox'];
911 $profile['poll'] = $apcontact['outbox'];
912 $profile['pubkey'] = $apcontact['pubkey'];
913 $profile['baseurl'] = $apcontact['baseurl'];
915 // Remove all "null" fields
916 foreach ($profile as $field => $content) {
917 if (is_null($content)) {
918 unset($profile[$field]);
930 * @param integer $uid User ID
932 public static function processInbox($body, $header, $uid)
934 $http_signer = HTTPSignature::getSigner($body, $header);
935 if (empty($http_signer)) {
936 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
939 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
942 $activity = json_decode($body, true);
944 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
945 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
947 if (empty($activity)) {
948 logger('Invalid body.', LOGGER_DEBUG);
952 if (LDSignature::isSigned($activity)) {
953 $ld_signer = LDSignature::getSigner($activity);
954 if (empty($ld_signer)) {
955 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
957 if (!empty($ld_signer && ($actor == $http_signer))) {
958 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
959 $trust_source = true;
960 } elseif (!empty($ld_signer)) {
961 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
962 $trust_source = true;
963 } elseif ($actor == $http_signer) {
964 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
965 $trust_source = true;
967 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
968 $trust_source = false;
970 } elseif ($actor == $http_signer) {
971 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
972 $trust_source = true;
974 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
975 $trust_source = false;
978 self::processActivity($activity, $body, $uid, $trust_source);
985 * @param integer $uid User ID
987 public static function fetchOutbox($url, $uid)
989 $data = self::fetchContent($url);
994 if (!empty($data['orderedItems'])) {
995 $items = $data['orderedItems'];
996 } elseif (!empty($data['first']['orderedItems'])) {
997 $items = $data['first']['orderedItems'];
998 } elseif (!empty($data['first'])) {
999 self::fetchOutbox($data['first'], $uid);
1005 foreach ($items as $activity) {
1006 self::processActivity($activity, '', $uid, true);
1013 * @param array $activity
1014 * @param integer $uid User ID
1015 * @param $trust_source
1019 private static function prepareObjectData($activity, $uid, &$trust_source)
1021 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
1022 if (empty($actor)) {
1023 logger('Empty actor', LOGGER_DEBUG);
1027 // Fetch all receivers from to, cc, bto and bcc
1028 $receivers = self::getReceivers($activity, $actor);
1030 // When it is a delivery to a personal inbox we add that user to the receivers
1032 $owner = User::getOwnerDataById($uid);
1033 $additional = ['uid:' . $uid => $uid];
1034 $receivers = array_merge($receivers, $additional);
1037 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
1039 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
1040 if (empty($object_id)) {
1041 logger('No object found', LOGGER_DEBUG);
1045 // Fetch the content only on activities where this matters
1046 if (in_array($activity['type'], ['Create', 'Announce'])) {
1047 $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
1048 if (empty($object_data)) {
1049 logger("Object data couldn't be processed", LOGGER_DEBUG);
1052 // We had been able to retrieve the object data - so we can trust the source
1053 $trust_source = true;
1054 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
1055 // Create a mostly empty array out of the activity data (instead of the object).
1056 // This way we later don't have to check for the existence of ech individual array element.
1057 $object_data = self::processObject($activity);
1058 $object_data['name'] = $activity['type'];
1059 $object_data['author'] = $activity['actor'];
1060 $object_data['object'] = $object_id;
1061 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
1064 $object_data['id'] = $activity['id'];
1065 $object_data['object'] = $activity['object'];
1066 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1069 $object_data = self::addActivityFields($object_data, $activity);
1071 $object_data['type'] = $activity['type'];
1072 $object_data['owner'] = $actor;
1073 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
1075 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
1077 return $object_data;
1083 * @param array $activity
1085 * @param integer $uid User ID
1086 * @param $trust_source
1088 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
1090 if (empty($activity['type'])) {
1091 logger('Empty type', LOGGER_DEBUG);
1095 if (empty($activity['object'])) {
1096 logger('Empty object', LOGGER_DEBUG);
1100 if (empty($activity['actor'])) {
1101 logger('Empty actor', LOGGER_DEBUG);
1106 // $trust_source is called by reference and is set to true if the content was retrieved successfully
1107 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
1108 if (empty($object_data)) {
1109 logger('No object data found', LOGGER_DEBUG);
1113 if (!$trust_source) {
1114 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
1117 switch ($activity['type']) {
1120 self::createItem($object_data, $body);
1124 self::likeItem($object_data, $body);
1128 self::dislikeItem($object_data, $body);
1132 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
1134 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
1135 self::updatePerson($object_data, $body);
1140 if ($object_data['object_type'] == 'Tombstone') {
1141 self::deleteItem($object_data, $body);
1142 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
1143 self::deletePerson($object_data, $body);
1148 self::followUser($object_data);
1152 if ($object_data['object_type'] == 'Follow') {
1153 self::acceptFollowUser($object_data);
1158 if ($object_data['object_type'] == 'Follow') {
1159 self::rejectFollowUser($object_data);
1164 if ($object_data['object_type'] == 'Follow') {
1165 self::undoFollowUser($object_data);
1166 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1167 self::undoActivity($object_data);
1172 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
1180 * @param array $activity
1185 private static function getReceivers($activity, $actor)
1189 // When it is an answer, we inherite the receivers from the parent
1190 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1191 if (!empty($replyto)) {
1192 $parents = Item::select(['uid'], ['uri' => $replyto]);
1193 while ($parent = Item::fetch($parents)) {
1194 $receivers['uid:' . $parent['uid']] = $parent['uid'];
1198 if (!empty($actor)) {
1199 $profile = APContact::getByURL($actor);
1200 $followers = defaults($profile, 'followers', '');
1202 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
1204 logger('Empty actor', LOGGER_DEBUG);
1208 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
1209 if (empty($activity[$element])) {
1213 // The receiver can be an array or a string
1214 if (is_string($activity[$element])) {
1215 $activity[$element] = [$activity[$element]];
1218 foreach ($activity[$element] as $receiver) {
1219 if ($receiver == self::PUBLIC_COLLECTION) {
1220 $receivers['uid:0'] = 0;
1223 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
1224 // This will most likely catch all OStatus connections to Mastodon
1225 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
1226 , 'archive' => false, 'pending' => false];
1227 $contacts = DBA::select('contact', ['uid'], $condition);
1228 while ($contact = DBA::fetch($contacts)) {
1229 if ($contact['uid'] != 0) {
1230 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1233 DBA::close($contacts);
1236 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
1237 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1238 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
1239 $contacts = DBA::select('contact', ['uid'], $condition);
1240 while ($contact = DBA::fetch($contacts)) {
1241 if ($contact['uid'] != 0) {
1242 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1245 DBA::close($contacts);
1249 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1250 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1251 if (!DBA::isResult($contact)) {
1254 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1258 self::switchContacts($receivers, $actor);
1267 * @param integer $uid User ID
1270 private static function switchContact($cid, $uid, $url)
1272 $profile = ActivityPub::probeProfile($url);
1273 if (empty($profile)) {
1277 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
1279 $photo = $profile['photo'];
1280 unset($profile['photo']);
1281 unset($profile['baseurl']);
1283 $profile['nurl'] = normalise_link($profile['url']);
1284 DBA::update('contact', $profile, ['id' => $cid]);
1286 Contact::updateAvatar($photo, $uid, $cid);
1295 private static function switchContacts($receivers, $actor)
1297 if (empty($actor)) {
1301 foreach ($receivers as $receiver) {
1302 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
1303 if (DBA::isResult($contact)) {
1304 self::switchContact($contact['id'], $receiver, $actor);
1307 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
1308 if (DBA::isResult($contact)) {
1309 self::switchContact($contact['id'], $receiver, $actor);
1317 * @param $object_data
1318 * @param array $activity
1322 private static function addActivityFields($object_data, $activity)
1324 if (!empty($activity['published']) && empty($object_data['published'])) {
1325 $object_data['published'] = $activity['published'];
1328 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1329 $object_data['updated'] = $activity['updated'];
1332 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1333 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1336 if (!empty($activity['instrument'])) {
1337 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1339 return $object_data;
1347 * @param $trust_source
1351 private static function fetchObject($object_id, $object = [], $trust_source = false)
1353 if (!$trust_source || is_string($object)) {
1354 $data = self::fetchContent($object_id);
1356 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
1359 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
1362 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
1366 if (is_string($data)) {
1367 $item = Item::selectFirst([], ['uri' => $data]);
1368 if (!DBA::isResult($item)) {
1369 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1372 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
1373 $data = self::createNote($item);
1376 if (empty($data['type'])) {
1377 logger('Empty type', LOGGER_DEBUG);
1381 if (in_array($data['type'], self::CONTENT_TYPES)) {
1382 return self::processObject($data);
1385 if ($data['type'] == 'Announce') {
1386 if (empty($data['object'])) {
1389 return self::fetchObject($data['object']);
1392 logger('Unhandled object type: ' . $data['type'], LOGGER_DEBUG);
1402 private static function processObject($object)
1404 if (empty($object['id'])) {
1409 $object_data['object_type'] = $object['type'];
1410 $object_data['id'] = $object['id'];
1412 if (!empty($object['inReplyTo'])) {
1413 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1415 $object_data['reply-to-id'] = $object_data['id'];
1418 $object_data['published'] = defaults($object, 'published', null);
1419 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1421 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1422 $object_data['published'] = $object_data['updated'];
1425 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
1426 if (empty($actor)) {
1427 $actor = defaults($object, 'actor', null);
1430 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
1431 $object_data['owner'] = $object_data['author'] = $actor;
1432 $object_data['context'] = defaults($object, 'context', null);
1433 $object_data['conversation'] = defaults($object, 'conversation', null);
1434 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1435 $object_data['name'] = defaults($object, 'title', null);
1436 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1437 $object_data['summary'] = defaults($object, 'summary', null);
1438 $object_data['content'] = defaults($object, 'content', null);
1439 $object_data['source'] = defaults($object, 'source', null);
1440 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1441 $object_data['attachments'] = defaults($object, 'attachment', null);
1442 $object_data['tags'] = defaults($object, 'tag', null);
1443 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1444 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1445 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1447 // Common object data:
1450 // @context, type, actor, signature, mediaType, duration, replies, icon
1452 // Also missing: (Defined in the standard, but currently unused)
1453 // audience, preview, endTime, startTime, generator, image
1458 // contentMap, announcement_count, announcements, context_id, likes, like_count
1459 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1464 // category, licence, language, commentsEnabled
1467 // views, waitTranscoding, state, support, subtitleLanguage
1468 // likes, dislikes, shares, comments
1470 return $object_data;
1474 * @brief Converts mentions from Pleroma into the Friendica format
1476 * @param string $body
1478 * @return converted body
1480 private static function convertMentions($body)
1482 $URLSearchString = "^\[\]";
1483 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1489 * @brief Constructs a string with tags for a given tag array
1491 * @param array $tags
1492 * @param boolean $sensitive
1494 * @return string with tags
1496 private static function constructTagList($tags, $sensitive)
1503 foreach ($tags as $tag) {
1504 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1505 if (!empty($tag_text)) {
1509 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1513 /// @todo add nsfw for $sensitive
1521 * @param $attachments
1522 * @param array $item
1524 * @return item array
1526 private static function constructAttachList($attachments, $item)
1528 if (empty($attachments)) {
1532 foreach ($attachments as $attach) {
1533 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1534 if ($filetype == 'image') {
1535 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1537 if (!empty($item["attach"])) {
1538 $item["attach"] .= ',';
1540 $item["attach"] = '';
1542 if (!isset($attach['length'])) {
1543 $attach['length'] = "0";
1545 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1555 * @param array $activity
1558 private static function createItem($activity, $body)
1561 $item['verb'] = ACTIVITY_POST;
1562 $item['parent-uri'] = $activity['reply-to-id'];
1564 if ($activity['reply-to-id'] == $activity['id']) {
1565 $item['gravity'] = GRAVITY_PARENT;
1566 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1568 $item['gravity'] = GRAVITY_COMMENT;
1569 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1572 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
1573 logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
1574 self::fetchMissingActivity($activity['reply-to-id'], $activity);
1577 self::postItem($activity, $item, $body);
1583 * @param array $activity
1586 private static function likeItem($activity, $body)
1589 $item['verb'] = ACTIVITY_LIKE;
1590 $item['parent-uri'] = $activity['object'];
1591 $item['gravity'] = GRAVITY_ACTIVITY;
1592 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1594 self::postItem($activity, $item, $body);
1598 * @brief Delete items
1600 * @param array $activity
1603 private static function deleteItem($activity)
1605 $owner = Contact::getIdForURL($activity['owner']);
1606 $object = JsonLD::fetchElement($activity, 'object', 'id');
1607 logger('Deleting item ' . $object . ' from ' . $owner, LOGGER_DEBUG);
1608 Item::delete(['uri' => $object, 'owner-id' => $owner]);
1614 * @param array $activity
1617 private static function dislikeItem($activity, $body)
1620 $item['verb'] = ACTIVITY_DISLIKE;
1621 $item['parent-uri'] = $activity['object'];
1622 $item['gravity'] = GRAVITY_ACTIVITY;
1623 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1625 self::postItem($activity, $item, $body);
1631 * @param array $activity
1632 * @param array $item
1635 private static function postItem($activity, $item, $body)
1637 /// @todo What to do with $activity['context']?
1639 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
1640 logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
1644 $item['network'] = Protocol::ACTIVITYPUB;
1645 $item['private'] = !in_array(0, $activity['receiver']);
1646 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1647 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1648 $item['uri'] = $activity['id'];
1649 $item['created'] = $activity['published'];
1650 $item['edited'] = $activity['updated'];
1651 $item['guid'] = $activity['diaspora:guid'];
1652 $item['title'] = HTML::toBBCode($activity['name']);
1653 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1654 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1655 $item['location'] = $activity['location'];
1656 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1657 $item['app'] = $activity['service'];
1658 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1660 $item = self::constructAttachList($activity['attachments'], $item);
1662 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1663 if (!empty($source)) {
1664 $item['body'] = $source;
1667 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1668 $item['source'] = $body;
1669 $item['conversation-href'] = $activity['context'];
1670 $item['conversation-uri'] = $activity['conversation'];
1672 foreach ($activity['receiver'] as $receiver) {
1673 $item['uid'] = $receiver;
1674 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1676 if (($receiver != 0) && empty($item['contact-id'])) {
1677 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1680 $item_id = Item::insert($item);
1681 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1691 private static function fetchMissingActivity($url, $child)
1693 if (Config::get('system', 'ostatus_full_threads')) {
1697 $object = ActivityPub::fetchContent($url);
1698 if (empty($object)) {
1699 logger('Activity ' . $url . ' was not fetchable, aborting.');
1704 $activity['@context'] = $object['@context'];
1705 unset($object['@context']);
1706 $activity['id'] = $object['id'];
1707 $activity['to'] = defaults($object, 'to', []);
1708 $activity['cc'] = defaults($object, 'cc', []);
1709 $activity['actor'] = $child['author'];
1710 $activity['object'] = $object;
1711 $activity['published'] = $object['published'];
1712 $activity['type'] = 'Create';
1714 self::processActivity($activity);
1715 logger('Activity ' . $url . ' had been fetched and processed.');
1719 * @brief perform a "follow" request
1721 * @param array $activity
1723 private static function followUser($activity)
1725 $actor = JsonLD::fetchElement($activity, 'object', 'id');
1726 $uid = User::getIdForURL($actor);
1731 $owner = User::getOwnerDataById($uid);
1733 $cid = Contact::getIdForURL($activity['owner'], $uid);
1735 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1740 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1741 'author-link' => $activity['owner']];
1743 Contact::addRelationship($owner, $contact, $item);
1744 $cid = Contact::getIdForURL($activity['owner'], $uid);
1749 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1750 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1751 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1754 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1755 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1759 * @brief Update the given profile
1761 * @param array $activity
1763 private static function updatePerson($activity)
1765 if (empty($activity['object']['id'])) {
1769 logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
1770 APContact::getByURL($activity['object']['id'], true);
1774 * @brief Delete the given profile
1776 * @param array $activity
1778 private static function deletePerson($activity)
1780 if (empty($activity['object']['id']) || empty($activity['object']['actor'])) {
1781 logger('Empty object id or actor.', LOGGER_DEBUG);
1785 if ($activity['object']['id'] != $activity['object']['actor']) {
1786 logger('Object id does not match actor.', LOGGER_DEBUG);
1790 $contacts = DBA::select('contact', ['id'], ['nurl' => normalise_link($activity['object']['id'])]);
1791 while ($contact = DBA::fetch($contacts)) {
1792 Contact::remove($contact["id"]);
1794 DBA::close($contacts);
1796 logger('Deleted contact ' . $activity['object']['id'], LOGGER_DEBUG);
1800 * @brief Accept a follow request
1802 * @param array $activity
1804 private static function acceptFollowUser($activity)
1806 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1807 $uid = User::getIdForURL($actor);
1812 $owner = User::getOwnerDataById($uid);
1814 $cid = Contact::getIdForURL($activity['owner'], $uid);
1816 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1820 $fields = ['pending' => false];
1822 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1823 if ($contact['rel'] == Contact::FOLLOWER) {
1824 $fields['rel'] = Contact::FRIEND;
1827 $condition = ['id' => $cid];
1828 DBA::update('contact', $fields, $condition);
1829 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1833 * @brief Reject a follow request
1835 * @param array $activity
1837 private static function rejectFollowUser($activity)
1839 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1840 $uid = User::getIdForURL($actor);
1845 $owner = User::getOwnerDataById($uid);
1847 $cid = Contact::getIdForURL($activity['owner'], $uid);
1849 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1853 if (DBA::exists('contact', ['id' => $cid, 'rel' => Contact::SHARING, 'pending' => true])) {
1854 Contact::remove($cid);
1855 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . ' - contact had been removed.', LOGGER_DEBUG);
1857 logger('Rejected contact request from contact ' . $cid . ' for user ' . $uid . '.', LOGGER_DEBUG);
1862 * @brief Undo activity like "like" or "dislike"
1864 * @param array $activity
1866 private static function undoActivity($activity)
1868 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
1869 if (empty($activity_url)) {
1873 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1874 if (empty($actor)) {
1878 $author_id = Contact::getIdForURL($actor);
1879 if (empty($author_id)) {
1883 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1887 * @brief Activity to remove a follower
1889 * @param array $activity
1891 private static function undoFollowUser($activity)
1893 $object = JsonLD::fetchElement($activity, 'object', 'object');
1894 $uid = User::getIdForURL($object);
1899 $owner = User::getOwnerDataById($uid);
1901 $cid = Contact::getIdForURL($activity['owner'], $uid);
1903 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1907 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1908 if (!DBA::isResult($contact)) {
1912 Contact::removeFollower($owner, $contact);
1913 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);