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
72 * - Queueing unsucessful deliveries
73 * - Polling the outboxes for missing content?
74 * - Possibly using the LD-JSON parser
78 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
79 const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
80 ['vcard' => 'http://www.w3.org/2006/vcard/ns#',
81 'diaspora' => 'https://diasporafoundation.org#',
82 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
83 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag']];
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::getProfileForUser($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::getProfileForUser($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 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
247 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
248 'account_removed' => false, 'verified' => true];
249 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
250 $user = DBA::selectFirst('user', $fields, $condition);
251 if (!DBA::isResult($user)) {
255 $fields = ['locality', 'region', 'country-name'];
256 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
257 if (!DBA::isResult($profile)) {
261 $fields = ['name', 'url', 'location', 'about', 'avatar'];
262 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
263 if (!DBA::isResult($contact)) {
267 $data = ['@context' => self::CONTEXT];
268 $data['id'] = $contact['url'];
269 $data['diaspora:guid'] = $user['guid'];
270 $data['type'] = $accounttype[$user['account-type']];
271 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
272 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
273 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
274 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
275 $data['preferredUsername'] = $user['nickname'];
276 $data['name'] = $contact['name'];
277 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
278 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
279 $data['summary'] = $contact['about'];
280 $data['url'] = $contact['url'];
281 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
282 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
283 'owner' => $contact['url'],
284 'publicKeyPem' => $user['pubkey']];
285 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
286 $data['icon'] = ['type' => 'Image',
287 'url' => $contact['avatar']];
289 // tags: https://kitty.town/@inmysocks/100656097926961126.json
294 * @brief Returns an array with permissions of a given item array
298 * @return array with permissions
300 private static function fetchPermissionBlockFromConversation($item)
302 if (empty($item['thr-parent'])) {
306 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
307 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
308 if (!DBA::isResult($conversation)) {
312 $activity = json_decode($conversation['source'], true);
314 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
315 $profile = APContact::getProfileByURL($actor);
317 $item_profile = APContact::getProfileByURL($item['author-link']);
318 $exclude[] = $item['author-link'];
320 if ($item['gravity'] == GRAVITY_PARENT) {
321 $exclude[] = $item['owner-link'];
324 $permissions['to'][] = $actor;
326 $elements = ['to', 'cc', 'bto', 'bcc'];
327 foreach ($elements as $element) {
328 if (empty($activity[$element])) {
331 if (is_string($activity[$element])) {
332 $activity[$element] = [$activity[$element]];
335 foreach ($activity[$element] as $receiver) {
336 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
337 $receiver = $item_profile['followers'];
339 if (!in_array($receiver, $exclude)) {
340 $permissions[$element][] = $receiver;
348 * @brief Creates an array of permissions from an item thread
352 * @return permission array
354 public static function createPermissionBlockForItem($item)
356 $data = ['to' => [], 'cc' => []];
358 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
360 $actor_profile = APContact::getProfileByURL($item['author-link']);
362 $terms = Term::tagArrayFromItemId($item['id']);
364 $contacts[$item['author-link']] = $item['author-link'];
366 if (!$item['private']) {
367 $data['to'][] = self::PUBLIC;
368 if (!empty($actor_profile['followers'])) {
369 $data['cc'][] = $actor_profile['followers'];
372 foreach ($terms as $term) {
373 if ($term['type'] != TERM_MENTION) {
376 $profile = APContact::getProfileByURL($term['url'], false);
377 if (!empty($profile) && empty($contacts[$profile['url']])) {
378 $data['cc'][] = $profile['url'];
379 $contacts[$profile['url']] = $profile['url'];
383 $receiver_list = Item::enumeratePermissions($item);
387 foreach ($terms as $term) {
388 if ($term['type'] != TERM_MENTION) {
391 $cid = Contact::getIdForURL($term['url'], $item['uid']);
392 if (!empty($cid) && in_array($cid, $receiver_list)) {
393 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
394 $data['to'][] = $contact['url'];
395 $contacts[$contact['url']] = $contact['url'];
399 foreach ($receiver_list as $receiver) {
400 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
401 if (empty($contacts[$contact['url']])) {
402 $data['cc'][] = $contact['url'];
403 $contacts[$contact['url']] = $contact['url'];
408 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
409 while ($parent = Item::fetch($parents)) {
410 // Don't include data from future posts
411 if ($parent['id'] >= $item['id']) {
415 $profile = APContact::getProfileByURL($parent['author-link'], false);
416 if (!empty($profile) && empty($contacts[$profile['url']])) {
417 $data['cc'][] = $profile['url'];
418 $contacts[$profile['url']] = $profile['url'];
421 if ($item['gravity'] != GRAVITY_PARENT) {
425 $profile = APContact::getProfileByURL($parent['owner-link'], false);
426 if (!empty($profile) && empty($contacts[$profile['url']])) {
427 $data['cc'][] = $profile['url'];
428 $contacts[$profile['url']] = $profile['url'];
431 DBA::close($parents);
433 if (empty($data['to'])) {
434 $data['to'] = $data['cc'];
442 * @brief Fetches an array of inboxes for the given item and user
445 * @param integer $uid User ID
447 * @return array with inboxes
449 public static function fetchTargetInboxes($item, $uid)
451 $permissions = self::createPermissionBlockForItem($item);
452 if (empty($permissions)) {
458 if ($item['gravity'] == GRAVITY_ACTIVITY) {
459 $item_profile = APContact::getProfileByURL($item['author-link']);
461 $item_profile = APContact::getProfileByURL($item['owner-link']);
464 $elements = ['to', 'cc', 'bto', 'bcc'];
465 foreach ($elements as $element) {
466 if (empty($permissions[$element])) {
470 foreach ($permissions[$element] as $receiver) {
471 if ($receiver == $item_profile['followers']) {
472 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
473 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
474 while ($contact = DBA::fetch($contacts)) {
475 $contact = defaults($contact, 'batch', $contact['notify']);
476 $inboxes[$contact] = $contact;
478 DBA::close($contacts);
480 $profile = APContact::getProfileByURL($receiver);
481 if (!empty($profile)) {
482 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
483 $inboxes[$target] = $target;
493 * @brief Returns the activity type of a given item
497 * @return activity type
499 public static function getTypeOfItem($item)
501 if ($item['verb'] == ACTIVITY_POST) {
502 if ($item['created'] == $item['edited']) {
507 } elseif ($item['verb'] == ACTIVITY_LIKE) {
509 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
511 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
513 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
515 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
516 $type = 'TentativeAccept';
525 * @brief Creates an activity array for a given item id
527 * @param integer $item_id
528 * @param boolean $object_mode Is the activity item is used inside another object?
530 * @return array of activity
532 public static function createActivityFromItem($item_id, $object_mode = false)
534 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
536 if (!DBA::isResult($item)) {
540 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
541 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
542 if (DBA::isResult($conversation)) {
543 $data = json_decode($conversation['source']);
549 $type = self::getTypeOfItem($item);
552 $data = ['@context' => self::CONTEXT];
554 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
556 } elseif ($item['deleted']) {
563 $data['id'] = $item['uri'] . '#' . $type;
564 $data['type'] = $type;
565 $data['actor'] = $item['author-link'];
567 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
569 if ($item["created"] != $item["edited"]) {
570 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
573 $data['context'] = self::fetchContextURLForItem($item);
575 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
577 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
578 $data['object'] = self::CreateNote($item);
579 } elseif ($data['type'] == 'Undo') {
580 $data['object'] = self::createActivityFromItem($item_id, true);
582 $data['object'] = $item['thr-parent'];
585 $owner = User::getOwnerDataById($item['uid']);
588 return LDSignature::sign($data, $owner);
595 * @brief Creates an object array for a given item id
597 * @param integer $item_id
599 * @return object array
601 public static function createObjectFromItemID($item_id)
603 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
605 if (!DBA::isResult($item)) {
609 $data = ['@context' => self::CONTEXT];
610 $data = array_merge($data, self::CreateNote($item));
616 * @brief Returns a tag array for a given item array
620 * @return array of tags
622 private static function createTagList($item)
626 $terms = Term::tagArrayFromItemId($item['id']);
627 foreach ($terms as $term) {
628 if ($term['type'] == TERM_MENTION) {
629 $contact = Contact::getDetailsByURL($term['url']);
630 if (!empty($contact['addr'])) {
631 $mention = '@' . $contact['addr'];
633 $mention = '@' . $term['url'];
636 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
643 * @brief Fetches the "context" value for a givem item array from the "conversation" table
647 * @return string with context url
649 private static function fetchContextURLForItem($item)
651 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
652 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
653 $context_uri = $conversation['conversation-href'];
654 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
655 $context_uri = $conversation['conversation-uri'];
657 $context_uri = str_replace('/object/', '/context/', $item['parent-uri']);
663 * @brief Creates a note/article object array
667 * @return object array
669 private static function CreateNote($item)
671 if (!empty($item['title'])) {
677 if ($item['deleted']) {
682 $data['id'] = $item['uri'];
683 $data['type'] = $type;
685 if ($item['deleted']) {
689 $data['summary'] = null; // Ignore by now
691 if ($item['uri'] != $item['thr-parent']) {
692 $data['inReplyTo'] = $item['thr-parent'];
694 $data['inReplyTo'] = null;
697 $data['diaspora:guid'] = $item['guid'];
698 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
700 if ($item["created"] != $item["edited"]) {
701 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
704 $data['url'] = $item['plink'];
705 $data['attributedTo'] = $item['author-link'];
706 $data['actor'] = $item['author-link'];
707 $data['sensitive'] = false; // - Query NSFW
708 $data['context'] = self::fetchContextURLForItem($item);
710 if (!empty($item['title'])) {
711 $data['name'] = BBCode::convert($item['title'], false, 7);
714 $data['content'] = BBCode::convert($item['body'], false, 7);
715 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
716 $data['attachment'] = []; // @ToDo
717 $data['tag'] = self::createTagList($item);
718 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
724 * @brief Transmits a given activity to a target
726 * @param array $activity
727 * @param string $target Target profile
728 * @param integer $uid User ID
730 public static function transmitActivity($activity, $target, $uid)
732 $profile = APContact::getProfileByURL($target);
734 $owner = User::getOwnerDataById($uid);
736 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
737 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
739 'actor' => $owner['url'],
740 'object' => $profile['url'],
741 'to' => $profile['url']];
743 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
745 $signed = LDSignature::sign($data, $owner);
746 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
750 * @brief Transmit a message that the contact request had been accepted
752 * @param string $target Target profile
754 * @param integer $uid User ID
756 public static function transmitContactAccept($target, $id, $uid)
758 $profile = APContact::getProfileByURL($target);
760 $owner = User::getOwnerDataById($uid);
761 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
762 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
764 'actor' => $owner['url'],
765 'object' => ['id' => $id, 'type' => 'Follow',
766 'actor' => $profile['url'],
767 'object' => $owner['url']],
768 'to' => $profile['url']];
770 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
772 $signed = LDSignature::sign($data, $owner);
773 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
779 * @param string $target Target profile
781 * @param integer $uid User ID
783 public static function transmitContactReject($target, $id, $uid)
785 $profile = APContact::getProfileByURL($target);
787 $owner = User::getOwnerDataById($uid);
788 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
789 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
791 'actor' => $owner['url'],
792 'object' => ['id' => $id, 'type' => 'Follow',
793 'actor' => $profile['url'],
794 'object' => $owner['url']],
795 'to' => $profile['url']];
797 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
799 $signed = LDSignature::sign($data, $owner);
800 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
806 * @param string $target Target profile
807 * @param integer $uid User ID
809 public static function transmitContactUndo($target, $uid)
811 $profile = APContact::getProfileByURL($target);
813 $id = System::baseUrl() . '/activity/' . System::createGUID();
815 $owner = User::getOwnerDataById($uid);
816 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
819 'actor' => $owner['url'],
820 'object' => ['id' => $id, 'type' => 'Follow',
821 'actor' => $owner['url'],
822 'object' => $profile['url']],
823 'to' => $profile['url']];
825 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
827 $signed = LDSignature::sign($data, $owner);
828 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
832 * Fetches ActivityPub content from the given url
834 * @param string $url content url
837 public static function fetchContent($url)
839 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
840 if (!$ret['success'] || empty($ret['body'])) {
843 return json_decode($ret['body'], true);
847 * Fetches a profile from the given url into an array that is compatible to Probe::uri
849 * @param string $url profile url
852 public static function probeProfile($url)
854 $apcontact = APContact::getProfileByURL($url, true);
855 if (empty($apcontact)) {
859 $profile = ['network' => Protocol::ACTIVITYPUB];
860 $profile['nick'] = $apcontact['nick'];
861 $profile['name'] = $apcontact['name'];
862 $profile['guid'] = $apcontact['uuid'];
863 $profile['url'] = $apcontact['url'];
864 $profile['addr'] = $apcontact['addr'];
865 $profile['alias'] = $apcontact['alias'];
866 $profile['photo'] = $apcontact['photo'];
867 // $profile['community']
868 // $profile['keywords']
869 // $profile['location']
870 $profile['about'] = $apcontact['about'];
871 $profile['batch'] = $apcontact['sharedinbox'];
872 $profile['notify'] = $apcontact['inbox'];
873 $profile['poll'] = $apcontact['outbox'];
874 $profile['pubkey'] = $apcontact['pubkey'];
875 $profile['baseurl'] = $apcontact['baseurl'];
877 // Remove all "null" fields
878 foreach ($profile as $field => $content) {
879 if (is_null($content)) {
880 unset($profile[$field]);
892 * @param integer $uid User ID
894 public static function processInbox($body, $header, $uid)
896 $http_signer = HTTPSignature::getSigner($body, $header);
897 if (empty($http_signer)) {
898 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
901 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
904 $activity = json_decode($body, true);
906 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
907 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
909 if (empty($activity)) {
910 logger('Invalid body.', LOGGER_DEBUG);
914 if (LDSignature::isSigned($activity)) {
915 $ld_signer = LDSignature::getSigner($activity);
916 if (empty($ld_signer)) {
917 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
919 if (!empty($ld_signer && ($actor == $http_signer))) {
920 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
921 $trust_source = true;
922 } elseif (!empty($ld_signer)) {
923 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
924 $trust_source = true;
925 } elseif ($actor == $http_signer) {
926 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
927 $trust_source = true;
929 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
930 $trust_source = false;
932 } elseif ($actor == $http_signer) {
933 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
934 $trust_source = true;
936 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
937 $trust_source = false;
940 self::processActivity($activity, $body, $uid, $trust_source);
947 * @param integer $uid User ID
949 public static function fetchOutbox($url, $uid)
951 $data = self::fetchContent($url);
956 if (!empty($data['orderedItems'])) {
957 $items = $data['orderedItems'];
958 } elseif (!empty($data['first']['orderedItems'])) {
959 $items = $data['first']['orderedItems'];
960 } elseif (!empty($data['first'])) {
961 self::fetchOutbox($data['first'], $uid);
967 foreach ($items as $activity) {
968 self::processActivity($activity, '', $uid, true);
975 * @param array $activity
976 * @param integer $uid User ID
977 * @param $trust_source
981 private static function prepareObjectData($activity, $uid, &$trust_source)
983 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
985 logger('Empty actor', LOGGER_DEBUG);
989 // Fetch all receivers from to, cc, bto and bcc
990 $receivers = self::getReceivers($activity, $actor);
992 // When it is a delivery to a personal inbox we add that user to the receivers
994 $owner = User::getOwnerDataById($uid);
995 $additional = ['uid:' . $uid => $uid];
996 $receivers = array_merge($receivers, $additional);
999 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
1001 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
1002 if (empty($object_id)) {
1003 logger('No object found', LOGGER_DEBUG);
1007 // Fetch the content only on activities where this matters
1008 if (in_array($activity['type'], ['Create', 'Announce'])) {
1009 $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
1010 if (empty($object_data)) {
1011 logger("Object data couldn't be processed", LOGGER_DEBUG);
1014 // We had been able to retrieve the object data - so we can trust the source
1015 $trust_source = true;
1016 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
1017 // Create a mostly empty array out of the activity data (instead of the object).
1018 // This way we later don't have to check for the existence of ech individual array element.
1019 $object_data = self::ProcessObject($activity);
1020 $object_data['name'] = $activity['type'];
1021 $object_data['author'] = $activity['actor'];
1022 $object_data['object'] = $object_id;
1023 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
1026 $object_data['id'] = $activity['id'];
1027 $object_data['object'] = $activity['object'];
1028 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1031 $object_data = self::addActivityFields($object_data, $activity);
1033 $object_data['type'] = $activity['type'];
1034 $object_data['owner'] = $actor;
1035 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
1037 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
1039 return $object_data;
1045 * @param array $activity
1047 * @param integer $uid User ID
1048 * @param $trust_source
1050 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
1052 if (empty($activity['type'])) {
1053 logger('Empty type', LOGGER_DEBUG);
1057 if (empty($activity['object'])) {
1058 logger('Empty object', LOGGER_DEBUG);
1062 if (empty($activity['actor'])) {
1063 logger('Empty actor', LOGGER_DEBUG);
1068 // $trust_source is called by reference and is set to true if the content was retrieved successfully
1069 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
1070 if (empty($object_data)) {
1071 logger('No object data found', LOGGER_DEBUG);
1075 if (!$trust_source) {
1076 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
1079 switch ($activity['type']) {
1082 self::createItem($object_data, $body);
1086 self::likeItem($object_data, $body);
1090 self::dislikeItem($object_data, $body);
1094 if (in_array($object_data['object_type'], ['Person', 'Organization', 'Service', 'Group', 'Application'])) {
1095 self::updatePerson($object_data, $body);
1103 self::followUser($object_data);
1107 if ($object_data['object_type'] == 'Follow') {
1108 self::acceptFollowUser($object_data);
1113 if ($object_data['object_type'] == 'Follow') {
1114 self::undoFollowUser($object_data);
1115 } elseif (in_array($object_data['object_type'], ['Like', 'Dislike', 'Accept', 'Reject', 'TentativeAccept'])) {
1116 self::undoActivity($object_data);
1121 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
1129 * @param array $activity
1134 private static function getReceivers($activity, $actor)
1138 // When it is an answer, we inherite the receivers from the parent
1139 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1140 if (!empty($replyto)) {
1141 $parents = Item::select(['uid'], ['uri' => $replyto]);
1142 while ($parent = Item::fetch($parents)) {
1143 $receivers['uid:' . $parent['uid']] = $parent['uid'];
1147 if (!empty($actor)) {
1148 $profile = APContact::getProfileByURL($actor);
1149 $followers = defaults($profile, 'followers', '');
1151 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
1153 logger('Empty actor', LOGGER_DEBUG);
1157 $elements = ['to', 'cc', 'bto', 'bcc'];
1158 foreach ($elements as $element) {
1159 if (empty($activity[$element])) {
1163 // The receiver can be an arror or a string
1164 if (is_string($activity[$element])) {
1165 $activity[$element] = [$activity[$element]];
1168 foreach ($activity[$element] as $receiver) {
1169 if ($receiver == self::PUBLIC) {
1170 $receivers['uid:0'] = 0;
1173 if (($receiver == self::PUBLIC) && !empty($actor)) {
1174 // This will most likely catch all OStatus connections to Mastodon
1175 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1176 $contacts = DBA::select('contact', ['uid'], $condition);
1177 while ($contact = DBA::fetch($contacts)) {
1178 if ($contact['uid'] != 0) {
1179 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1182 DBA::close($contacts);
1185 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1186 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1187 'network' => Protocol::ACTIVITYPUB];
1188 $contacts = DBA::select('contact', ['uid'], $condition);
1189 while ($contact = DBA::fetch($contacts)) {
1190 if ($contact['uid'] != 0) {
1191 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1194 DBA::close($contacts);
1198 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1199 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1200 if (!DBA::isResult($contact)) {
1203 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1207 self::switchContacts($receivers, $actor);
1216 * @param integer $uid User ID
1219 private static function switchContact($cid, $uid, $url)
1221 $profile = ActivityPub::probeProfile($url);
1222 if (empty($profile)) {
1226 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
1228 $photo = $profile['photo'];
1229 unset($profile['photo']);
1230 unset($profile['baseurl']);
1232 $profile['nurl'] = normalise_link($profile['url']);
1233 DBA::update('contact', $profile, ['id' => $cid]);
1235 Contact::updateAvatar($photo, $uid, $cid);
1244 private static function switchContacts($receivers, $actor)
1246 if (empty($actor)) {
1250 foreach ($receivers as $receiver) {
1251 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
1252 if (DBA::isResult($contact)) {
1253 self::switchContact($contact['id'], $receiver, $actor);
1256 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
1257 if (DBA::isResult($contact)) {
1258 self::switchContact($contact['id'], $receiver, $actor);
1266 * @param $object_data
1267 * @param array $activity
1271 private static function addActivityFields($object_data, $activity)
1273 if (!empty($activity['published']) && empty($object_data['published'])) {
1274 $object_data['published'] = $activity['published'];
1277 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1278 $object_data['updated'] = $activity['updated'];
1281 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1282 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1285 if (!empty($activity['instrument'])) {
1286 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1288 return $object_data;
1296 * @param $trust_source
1300 private static function fetchObject($object_id, $object = [], $trust_source = false)
1302 if (!$trust_source || is_string($object)) {
1303 $data = self::fetchContent($object_id);
1305 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
1308 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
1311 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
1315 if (is_string($data)) {
1316 $item = Item::selectFirst([], ['uri' => $data]);
1317 if (!DBA::isResult($item)) {
1318 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1321 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
1322 $data = self::CreateNote($item);
1325 if (empty($data['type'])) {
1326 logger('Empty type', LOGGER_DEBUG);
1330 switch ($data['type']) {
1334 return self::ProcessObject($data);
1337 if (empty($data['object'])) {
1340 return self::fetchObject($data['object']);
1347 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1359 private static function ProcessObject(&$object)
1361 if (empty($object['id'])) {
1366 $object_data['object_type'] = $object['type'];
1367 $object_data['id'] = $object['id'];
1369 if (!empty($object['inReplyTo'])) {
1370 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1372 $object_data['reply-to-id'] = $object_data['id'];
1375 $object_data['published'] = defaults($object, 'published', null);
1376 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1378 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1379 $object_data['published'] = $object_data['updated'];
1382 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
1383 if (empty($actor)) {
1384 $actor = defaults($object, 'actor', null);
1387 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
1388 $object_data['owner'] = $object_data['author'] = $actor;
1389 $object_data['context'] = defaults($object, 'context', null);
1390 $object_data['conversation'] = defaults($object, 'conversation', null);
1391 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1392 $object_data['name'] = defaults($object, 'title', null);
1393 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1394 $object_data['summary'] = defaults($object, 'summary', null);
1395 $object_data['content'] = defaults($object, 'content', null);
1396 $object_data['source'] = defaults($object, 'source', null);
1397 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1398 $object_data['attachments'] = defaults($object, 'attachment', null);
1399 $object_data['tags'] = defaults($object, 'tag', null);
1400 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1401 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1402 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1404 // Common object data:
1407 // @context, type, actor, signature, mediaType, duration, replies, icon
1409 // Also missing: (Defined in the standard, but currently unused)
1410 // audience, preview, endTime, startTime, generator, image
1415 // contentMap, announcement_count, announcements, context_id, likes, like_count
1416 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1421 // category, licence, language, commentsEnabled
1424 // views, waitTranscoding, state, support, subtitleLanguage
1425 // likes, dislikes, shares, comments
1427 return $object_data;
1431 * @brief Converts mentions from Pleroma into the Friendica format
1433 * @param string $body
1435 * @return converted body
1437 private static function convertMentions($body)
1439 $URLSearchString = "^\[\]";
1440 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1446 * @brief Constructs a string with tags for a given tag array
1448 * @param array $tags
1449 * @param boolean $sensitive
1451 * @return string with tags
1453 private static function constructTagList($tags, $sensitive)
1460 foreach ($tags as $tag) {
1461 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1462 if (!empty($tag_text)) {
1466 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1470 /// @todo add nsfw for $sensitive
1478 * @param $attachments
1479 * @param array $item
1481 * @return item array
1483 private static function constructAttachList($attachments, $item)
1485 if (empty($attachments)) {
1489 foreach ($attachments as $attach) {
1490 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1491 if ($filetype == 'image') {
1492 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1494 if (!empty($item["attach"])) {
1495 $item["attach"] .= ',';
1497 $item["attach"] = '';
1499 if (!isset($attach['length'])) {
1500 $attach['length'] = "0";
1502 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1512 * @param array $activity
1515 private static function createItem($activity, $body)
1518 $item['verb'] = ACTIVITY_POST;
1519 $item['parent-uri'] = $activity['reply-to-id'];
1521 if ($activity['reply-to-id'] == $activity['id']) {
1522 $item['gravity'] = GRAVITY_PARENT;
1523 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1525 $item['gravity'] = GRAVITY_COMMENT;
1526 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1529 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
1530 logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
1531 self::fetchMissingActivity($activity['reply-to-id'], $activity);
1534 self::postItem($activity, $item, $body);
1540 * @param array $activity
1543 private static function likeItem($activity, $body)
1546 $item['verb'] = ACTIVITY_LIKE;
1547 $item['parent-uri'] = $activity['object'];
1548 $item['gravity'] = GRAVITY_ACTIVITY;
1549 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1551 self::postItem($activity, $item, $body);
1557 * @param array $activity
1560 private static function dislikeItem($activity, $body)
1563 $item['verb'] = ACTIVITY_DISLIKE;
1564 $item['parent-uri'] = $activity['object'];
1565 $item['gravity'] = GRAVITY_ACTIVITY;
1566 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1568 self::postItem($activity, $item, $body);
1574 * @param array $activity
1575 * @param array $item
1578 private static function postItem($activity, $item, $body)
1580 /// @todo What to do with $activity['context']?
1582 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
1583 logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
1587 $item['network'] = Protocol::ACTIVITYPUB;
1588 $item['private'] = !in_array(0, $activity['receiver']);
1589 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1590 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1591 $item['uri'] = $activity['id'];
1592 $item['created'] = $activity['published'];
1593 $item['edited'] = $activity['updated'];
1594 $item['guid'] = $activity['diaspora:guid'];
1595 $item['title'] = HTML::toBBCode($activity['name']);
1596 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1597 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1598 $item['location'] = $activity['location'];
1599 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1600 $item['app'] = $activity['service'];
1601 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1603 $item = self::constructAttachList($activity['attachments'], $item);
1605 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1606 if (!empty($source)) {
1607 $item['body'] = $source;
1610 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1611 $item['source'] = $body;
1612 $item['conversation-href'] = $activity['context'];
1613 $item['conversation-uri'] = $activity['conversation'];
1615 foreach ($activity['receiver'] as $receiver) {
1616 $item['uid'] = $receiver;
1617 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1619 if (($receiver != 0) && empty($item['contact-id'])) {
1620 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1623 $item_id = Item::insert($item);
1624 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1634 private static function fetchMissingActivity($url, $child)
1636 if (Config::get('system', 'ostatus_full_threads')) {
1640 $object = ActivityPub::fetchContent($url);
1641 if (empty($object)) {
1642 logger('Activity ' . $url . ' was not fetchable, aborting.');
1647 $activity['@context'] = $object['@context'];
1648 unset($object['@context']);
1649 $activity['id'] = $object['id'];
1650 $activity['to'] = defaults($object, 'to', []);
1651 $activity['cc'] = defaults($object, 'cc', []);
1652 $activity['actor'] = $child['author'];
1653 $activity['object'] = $object;
1654 $activity['published'] = $object['published'];
1655 $activity['type'] = 'Create';
1657 self::processActivity($activity);
1658 logger('Activity ' . $url . ' had been fetched and processed.');
1662 * @brief Returns the user id of a given profile url
1664 * @param string $profile
1666 * @return integer user id
1668 private static function getUserOfProfile($profile)
1670 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($profile), 'self' => true]);
1671 if (!DBA::isResult($self)) {
1674 return $self['uid'];
1679 * @brief perform a "follow" request
1681 * @param array $activity
1683 private static function followUser($activity)
1685 $actor = JsonLD::fetchElement($activity, 'object', 'id');
1686 $uid = self::getUserOfProfile($actor);
1691 $owner = User::getOwnerDataById($uid);
1693 $cid = Contact::getIdForURL($activity['owner'], $uid);
1695 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1700 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1701 'author-link' => $activity['owner']];
1703 Contact::addRelationship($owner, $contact, $item);
1704 $cid = Contact::getIdForURL($activity['owner'], $uid);
1709 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1710 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1711 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1714 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1715 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1719 * @brief Update the given profile
1721 * @param array $activity
1723 private static function updatePerson($activity)
1725 if (empty($activity['object']['id'])) {
1729 logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
1730 APContact::getProfileByURL($activity['object']['id'], true);
1734 * @brief Accept a follow request
1736 * @param array $activity
1738 private static function acceptFollowUser($activity)
1740 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1741 $uid = self::getUserOfProfile($actor);
1746 $owner = User::getOwnerDataById($uid);
1748 $cid = Contact::getIdForURL($activity['owner'], $uid);
1750 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1754 $fields = ['pending' => false];
1756 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1757 if ($contact['rel'] == Contact::FOLLOWER) {
1758 $fields['rel'] = Contact::FRIEND;
1761 $condition = ['id' => $cid];
1762 DBA::update('contact', $fields, $condition);
1763 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1767 * @brief Undo activity like "like" or "dislike"
1769 * @param array $activity
1771 private static function undoActivity($activity)
1773 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
1774 if (empty($activity_url)) {
1778 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1779 if (empty($actor)) {
1783 $author_id = Contact::getIdForURL($actor);
1784 if (empty($author_id)) {
1788 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1792 * @brief Activity to remove a follower
1794 * @param array $activity
1796 private static function undoFollowUser($activity)
1798 $object = JsonLD::fetchElement($activity, 'object', 'object');
1799 $uid = self::getUserOfProfile($object);
1804 $owner = User::getOwnerDataById($uid);
1806 $cid = Contact::getIdForURL($activity['owner'], $uid);
1808 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1812 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1813 if (!DBA::isResult($contact)) {
1817 Contact::removeFollower($owner, $contact);
1818 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);