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/ns/',
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"];
717 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
718 $data['diaspora:comment'] = $item['signed_text'];
721 $data['attachment'] = []; // @ToDo
722 $data['tag'] = self::createTagList($item);
723 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
729 * @brief Transmits a given activity to a target
731 * @param array $activity
732 * @param string $target Target profile
733 * @param integer $uid User ID
735 public static function transmitActivity($activity, $target, $uid)
737 $profile = APContact::getProfileByURL($target);
739 $owner = User::getOwnerDataById($uid);
741 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
742 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
744 'actor' => $owner['url'],
745 'object' => $profile['url'],
746 'to' => $profile['url']];
748 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
750 $signed = LDSignature::sign($data, $owner);
751 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
755 * @brief Transmit a message that the contact request had been accepted
757 * @param string $target Target profile
759 * @param integer $uid User ID
761 public static function transmitContactAccept($target, $id, $uid)
763 $profile = APContact::getProfileByURL($target);
765 $owner = User::getOwnerDataById($uid);
766 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
767 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
769 'actor' => $owner['url'],
770 'object' => ['id' => $id, 'type' => 'Follow',
771 'actor' => $profile['url'],
772 'object' => $owner['url']],
773 'to' => $profile['url']];
775 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
777 $signed = LDSignature::sign($data, $owner);
778 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
784 * @param string $target Target profile
786 * @param integer $uid User ID
788 public static function transmitContactReject($target, $id, $uid)
790 $profile = APContact::getProfileByURL($target);
792 $owner = User::getOwnerDataById($uid);
793 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
794 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
796 'actor' => $owner['url'],
797 'object' => ['id' => $id, 'type' => 'Follow',
798 'actor' => $profile['url'],
799 'object' => $owner['url']],
800 'to' => $profile['url']];
802 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
804 $signed = LDSignature::sign($data, $owner);
805 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
811 * @param string $target Target profile
812 * @param integer $uid User ID
814 public static function transmitContactUndo($target, $uid)
816 $profile = APContact::getProfileByURL($target);
818 $id = System::baseUrl() . '/activity/' . System::createGUID();
820 $owner = User::getOwnerDataById($uid);
821 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
824 'actor' => $owner['url'],
825 'object' => ['id' => $id, 'type' => 'Follow',
826 'actor' => $owner['url'],
827 'object' => $profile['url']],
828 'to' => $profile['url']];
830 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
832 $signed = LDSignature::sign($data, $owner);
833 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
837 * Fetches ActivityPub content from the given url
839 * @param string $url content url
842 public static function fetchContent($url)
844 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
845 if (!$ret['success'] || empty($ret['body'])) {
848 return json_decode($ret['body'], true);
852 * Fetches a profile from the given url into an array that is compatible to Probe::uri
854 * @param string $url profile url
857 public static function probeProfile($url)
859 $apcontact = APContact::getProfileByURL($url, true);
860 if (empty($apcontact)) {
864 $profile = ['network' => Protocol::ACTIVITYPUB];
865 $profile['nick'] = $apcontact['nick'];
866 $profile['name'] = $apcontact['name'];
867 $profile['guid'] = $apcontact['uuid'];
868 $profile['url'] = $apcontact['url'];
869 $profile['addr'] = $apcontact['addr'];
870 $profile['alias'] = $apcontact['alias'];
871 $profile['photo'] = $apcontact['photo'];
872 // $profile['community']
873 // $profile['keywords']
874 // $profile['location']
875 $profile['about'] = $apcontact['about'];
876 $profile['batch'] = $apcontact['sharedinbox'];
877 $profile['notify'] = $apcontact['inbox'];
878 $profile['poll'] = $apcontact['outbox'];
879 $profile['pubkey'] = $apcontact['pubkey'];
880 $profile['baseurl'] = $apcontact['baseurl'];
882 // Remove all "null" fields
883 foreach ($profile as $field => $content) {
884 if (is_null($content)) {
885 unset($profile[$field]);
897 * @param integer $uid User ID
899 public static function processInbox($body, $header, $uid)
901 $http_signer = HTTPSignature::getSigner($body, $header);
902 if (empty($http_signer)) {
903 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
906 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
909 $activity = json_decode($body, true);
911 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
912 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
914 if (empty($activity)) {
915 logger('Invalid body.', LOGGER_DEBUG);
919 if (LDSignature::isSigned($activity)) {
920 $ld_signer = LDSignature::getSigner($activity);
921 if (empty($ld_signer)) {
922 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
924 if (!empty($ld_signer && ($actor == $http_signer))) {
925 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
926 $trust_source = true;
927 } elseif (!empty($ld_signer)) {
928 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
929 $trust_source = true;
930 } elseif ($actor == $http_signer) {
931 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
932 $trust_source = true;
934 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
935 $trust_source = false;
937 } elseif ($actor == $http_signer) {
938 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
939 $trust_source = true;
941 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
942 $trust_source = false;
945 self::processActivity($activity, $body, $uid, $trust_source);
952 * @param integer $uid User ID
954 public static function fetchOutbox($url, $uid)
956 $data = self::fetchContent($url);
961 if (!empty($data['orderedItems'])) {
962 $items = $data['orderedItems'];
963 } elseif (!empty($data['first']['orderedItems'])) {
964 $items = $data['first']['orderedItems'];
965 } elseif (!empty($data['first'])) {
966 self::fetchOutbox($data['first'], $uid);
972 foreach ($items as $activity) {
973 self::processActivity($activity, '', $uid, true);
980 * @param array $activity
981 * @param integer $uid User ID
982 * @param $trust_source
986 private static function prepareObjectData($activity, $uid, &$trust_source)
988 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
990 logger('Empty actor', LOGGER_DEBUG);
994 // Fetch all receivers from to, cc, bto and bcc
995 $receivers = self::getReceivers($activity, $actor);
997 // When it is a delivery to a personal inbox we add that user to the receivers
999 $owner = User::getOwnerDataById($uid);
1000 $additional = ['uid:' . $uid => $uid];
1001 $receivers = array_merge($receivers, $additional);
1004 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
1006 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
1007 if (empty($object_id)) {
1008 logger('No object found', LOGGER_DEBUG);
1012 // Fetch the content only on activities where this matters
1013 if (in_array($activity['type'], ['Create', 'Announce'])) {
1014 $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
1015 if (empty($object_data)) {
1016 logger("Object data couldn't be processed", LOGGER_DEBUG);
1019 // We had been able to retrieve the object data - so we can trust the source
1020 $trust_source = true;
1021 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
1022 // Create a mostly empty array out of the activity data (instead of the object).
1023 // This way we later don't have to check for the existence of ech individual array element.
1024 $object_data = self::ProcessObject($activity);
1025 $object_data['name'] = $activity['type'];
1026 $object_data['author'] = $activity['actor'];
1027 $object_data['object'] = $object_id;
1028 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
1031 $object_data['id'] = $activity['id'];
1032 $object_data['object'] = $activity['object'];
1033 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1036 $object_data = self::addActivityFields($object_data, $activity);
1038 $object_data['type'] = $activity['type'];
1039 $object_data['owner'] = $actor;
1040 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
1042 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
1044 return $object_data;
1050 * @param array $activity
1052 * @param integer $uid User ID
1053 * @param $trust_source
1055 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
1057 if (empty($activity['type'])) {
1058 logger('Empty type', LOGGER_DEBUG);
1062 if (empty($activity['object'])) {
1063 logger('Empty object', LOGGER_DEBUG);
1067 if (empty($activity['actor'])) {
1068 logger('Empty actor', LOGGER_DEBUG);
1073 // $trust_source is called by reference and is set to true if the content was retrieved successfully
1074 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
1075 if (empty($object_data)) {
1076 logger('No object data found', LOGGER_DEBUG);
1080 if (!$trust_source) {
1081 logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
1084 switch ($activity['type']) {
1087 self::createItem($object_data, $body);
1091 self::likeItem($object_data, $body);
1095 self::dislikeItem($object_data, $body);
1099 if (in_array($object_data['object_type'], ['Person', 'Organization', 'Service', 'Group', 'Application'])) {
1100 self::updatePerson($object_data, $body);
1108 self::followUser($object_data);
1112 if ($object_data['object_type'] == 'Follow') {
1113 self::acceptFollowUser($object_data);
1118 if ($object_data['object_type'] == 'Follow') {
1119 self::undoFollowUser($object_data);
1120 } elseif (in_array($object_data['object_type'], ['Like', 'Dislike', 'Accept', 'Reject', 'TentativeAccept'])) {
1121 self::undoActivity($object_data);
1126 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
1134 * @param array $activity
1139 private static function getReceivers($activity, $actor)
1143 // When it is an answer, we inherite the receivers from the parent
1144 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1145 if (!empty($replyto)) {
1146 $parents = Item::select(['uid'], ['uri' => $replyto]);
1147 while ($parent = Item::fetch($parents)) {
1148 $receivers['uid:' . $parent['uid']] = $parent['uid'];
1152 if (!empty($actor)) {
1153 $profile = APContact::getProfileByURL($actor);
1154 $followers = defaults($profile, 'followers', '');
1156 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
1158 logger('Empty actor', LOGGER_DEBUG);
1162 $elements = ['to', 'cc', 'bto', 'bcc'];
1163 foreach ($elements as $element) {
1164 if (empty($activity[$element])) {
1168 // The receiver can be an arror or a string
1169 if (is_string($activity[$element])) {
1170 $activity[$element] = [$activity[$element]];
1173 foreach ($activity[$element] as $receiver) {
1174 if ($receiver == self::PUBLIC) {
1175 $receivers['uid:0'] = 0;
1178 if (($receiver == self::PUBLIC) && !empty($actor)) {
1179 // This will most likely catch all OStatus connections to Mastodon
1180 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1181 $contacts = DBA::select('contact', ['uid'], $condition);
1182 while ($contact = DBA::fetch($contacts)) {
1183 if ($contact['uid'] != 0) {
1184 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1187 DBA::close($contacts);
1190 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1191 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1192 'network' => Protocol::ACTIVITYPUB];
1193 $contacts = DBA::select('contact', ['uid'], $condition);
1194 while ($contact = DBA::fetch($contacts)) {
1195 if ($contact['uid'] != 0) {
1196 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1199 DBA::close($contacts);
1203 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1204 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1205 if (!DBA::isResult($contact)) {
1208 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1212 self::switchContacts($receivers, $actor);
1221 * @param integer $uid User ID
1224 private static function switchContact($cid, $uid, $url)
1226 $profile = ActivityPub::probeProfile($url);
1227 if (empty($profile)) {
1231 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
1233 $photo = $profile['photo'];
1234 unset($profile['photo']);
1235 unset($profile['baseurl']);
1237 $profile['nurl'] = normalise_link($profile['url']);
1238 DBA::update('contact', $profile, ['id' => $cid]);
1240 Contact::updateAvatar($photo, $uid, $cid);
1249 private static function switchContacts($receivers, $actor)
1251 if (empty($actor)) {
1255 foreach ($receivers as $receiver) {
1256 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
1257 if (DBA::isResult($contact)) {
1258 self::switchContact($contact['id'], $receiver, $actor);
1261 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
1262 if (DBA::isResult($contact)) {
1263 self::switchContact($contact['id'], $receiver, $actor);
1271 * @param $object_data
1272 * @param array $activity
1276 private static function addActivityFields($object_data, $activity)
1278 if (!empty($activity['published']) && empty($object_data['published'])) {
1279 $object_data['published'] = $activity['published'];
1282 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1283 $object_data['updated'] = $activity['updated'];
1286 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1287 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1290 if (!empty($activity['instrument'])) {
1291 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1293 return $object_data;
1301 * @param $trust_source
1305 private static function fetchObject($object_id, $object = [], $trust_source = false)
1307 if (!$trust_source || is_string($object)) {
1308 $data = self::fetchContent($object_id);
1310 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
1313 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
1316 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
1320 if (is_string($data)) {
1321 $item = Item::selectFirst([], ['uri' => $data]);
1322 if (!DBA::isResult($item)) {
1323 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1326 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
1327 $data = self::createNote($item);
1330 if (empty($data['type'])) {
1331 logger('Empty type', LOGGER_DEBUG);
1335 switch ($data['type']) {
1339 return self::ProcessObject($data);
1342 if (empty($data['object'])) {
1345 return self::fetchObject($data['object']);
1352 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1364 private static function ProcessObject(&$object)
1366 if (empty($object['id'])) {
1371 $object_data['object_type'] = $object['type'];
1372 $object_data['id'] = $object['id'];
1374 if (!empty($object['inReplyTo'])) {
1375 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1377 $object_data['reply-to-id'] = $object_data['id'];
1380 $object_data['published'] = defaults($object, 'published', null);
1381 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1383 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1384 $object_data['published'] = $object_data['updated'];
1387 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
1388 if (empty($actor)) {
1389 $actor = defaults($object, 'actor', null);
1392 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
1393 $object_data['owner'] = $object_data['author'] = $actor;
1394 $object_data['context'] = defaults($object, 'context', null);
1395 $object_data['conversation'] = defaults($object, 'conversation', null);
1396 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1397 $object_data['name'] = defaults($object, 'title', null);
1398 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1399 $object_data['summary'] = defaults($object, 'summary', null);
1400 $object_data['content'] = defaults($object, 'content', null);
1401 $object_data['source'] = defaults($object, 'source', null);
1402 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1403 $object_data['attachments'] = defaults($object, 'attachment', null);
1404 $object_data['tags'] = defaults($object, 'tag', null);
1405 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1406 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1407 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1409 // Common object data:
1412 // @context, type, actor, signature, mediaType, duration, replies, icon
1414 // Also missing: (Defined in the standard, but currently unused)
1415 // audience, preview, endTime, startTime, generator, image
1420 // contentMap, announcement_count, announcements, context_id, likes, like_count
1421 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1426 // category, licence, language, commentsEnabled
1429 // views, waitTranscoding, state, support, subtitleLanguage
1430 // likes, dislikes, shares, comments
1432 return $object_data;
1436 * @brief Converts mentions from Pleroma into the Friendica format
1438 * @param string $body
1440 * @return converted body
1442 private static function convertMentions($body)
1444 $URLSearchString = "^\[\]";
1445 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1451 * @brief Constructs a string with tags for a given tag array
1453 * @param array $tags
1454 * @param boolean $sensitive
1456 * @return string with tags
1458 private static function constructTagList($tags, $sensitive)
1465 foreach ($tags as $tag) {
1466 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1467 if (!empty($tag_text)) {
1471 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1475 /// @todo add nsfw for $sensitive
1483 * @param $attachments
1484 * @param array $item
1486 * @return item array
1488 private static function constructAttachList($attachments, $item)
1490 if (empty($attachments)) {
1494 foreach ($attachments as $attach) {
1495 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1496 if ($filetype == 'image') {
1497 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1499 if (!empty($item["attach"])) {
1500 $item["attach"] .= ',';
1502 $item["attach"] = '';
1504 if (!isset($attach['length'])) {
1505 $attach['length'] = "0";
1507 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1517 * @param array $activity
1520 private static function createItem($activity, $body)
1523 $item['verb'] = ACTIVITY_POST;
1524 $item['parent-uri'] = $activity['reply-to-id'];
1526 if ($activity['reply-to-id'] == $activity['id']) {
1527 $item['gravity'] = GRAVITY_PARENT;
1528 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1530 $item['gravity'] = GRAVITY_COMMENT;
1531 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1534 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
1535 logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
1536 self::fetchMissingActivity($activity['reply-to-id'], $activity);
1539 self::postItem($activity, $item, $body);
1545 * @param array $activity
1548 private static function likeItem($activity, $body)
1551 $item['verb'] = ACTIVITY_LIKE;
1552 $item['parent-uri'] = $activity['object'];
1553 $item['gravity'] = GRAVITY_ACTIVITY;
1554 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1556 self::postItem($activity, $item, $body);
1562 * @param array $activity
1565 private static function dislikeItem($activity, $body)
1568 $item['verb'] = ACTIVITY_DISLIKE;
1569 $item['parent-uri'] = $activity['object'];
1570 $item['gravity'] = GRAVITY_ACTIVITY;
1571 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1573 self::postItem($activity, $item, $body);
1579 * @param array $activity
1580 * @param array $item
1583 private static function postItem($activity, $item, $body)
1585 /// @todo What to do with $activity['context']?
1587 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
1588 logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
1592 $item['network'] = Protocol::ACTIVITYPUB;
1593 $item['private'] = !in_array(0, $activity['receiver']);
1594 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1595 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1596 $item['uri'] = $activity['id'];
1597 $item['created'] = $activity['published'];
1598 $item['edited'] = $activity['updated'];
1599 $item['guid'] = $activity['diaspora:guid'];
1600 $item['title'] = HTML::toBBCode($activity['name']);
1601 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1602 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1603 $item['location'] = $activity['location'];
1604 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1605 $item['app'] = $activity['service'];
1606 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1608 $item = self::constructAttachList($activity['attachments'], $item);
1610 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1611 if (!empty($source)) {
1612 $item['body'] = $source;
1615 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1616 $item['source'] = $body;
1617 $item['conversation-href'] = $activity['context'];
1618 $item['conversation-uri'] = $activity['conversation'];
1620 foreach ($activity['receiver'] as $receiver) {
1621 $item['uid'] = $receiver;
1622 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1624 if (($receiver != 0) && empty($item['contact-id'])) {
1625 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1628 $item_id = Item::insert($item);
1629 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1639 private static function fetchMissingActivity($url, $child)
1641 if (Config::get('system', 'ostatus_full_threads')) {
1645 $object = ActivityPub::fetchContent($url);
1646 if (empty($object)) {
1647 logger('Activity ' . $url . ' was not fetchable, aborting.');
1652 $activity['@context'] = $object['@context'];
1653 unset($object['@context']);
1654 $activity['id'] = $object['id'];
1655 $activity['to'] = defaults($object, 'to', []);
1656 $activity['cc'] = defaults($object, 'cc', []);
1657 $activity['actor'] = $child['author'];
1658 $activity['object'] = $object;
1659 $activity['published'] = $object['published'];
1660 $activity['type'] = 'Create';
1662 self::processActivity($activity);
1663 logger('Activity ' . $url . ' had been fetched and processed.');
1667 * @brief Returns the user id of a given profile url
1669 * @param string $profile
1671 * @return integer user id
1673 private static function getUserOfProfile($profile)
1675 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($profile), 'self' => true]);
1676 if (!DBA::isResult($self)) {
1679 return $self['uid'];
1684 * @brief perform a "follow" request
1686 * @param array $activity
1688 private static function followUser($activity)
1690 $actor = JsonLD::fetchElement($activity, 'object', 'id');
1691 $uid = self::getUserOfProfile($actor);
1696 $owner = User::getOwnerDataById($uid);
1698 $cid = Contact::getIdForURL($activity['owner'], $uid);
1700 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1705 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1706 'author-link' => $activity['owner']];
1708 Contact::addRelationship($owner, $contact, $item);
1709 $cid = Contact::getIdForURL($activity['owner'], $uid);
1714 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1715 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1716 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1719 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1720 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1724 * @brief Update the given profile
1726 * @param array $activity
1728 private static function updatePerson($activity)
1730 if (empty($activity['object']['id'])) {
1734 logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
1735 APContact::getProfileByURL($activity['object']['id'], true);
1739 * @brief Accept a follow request
1741 * @param array $activity
1743 private static function acceptFollowUser($activity)
1745 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1746 $uid = self::getUserOfProfile($actor);
1751 $owner = User::getOwnerDataById($uid);
1753 $cid = Contact::getIdForURL($activity['owner'], $uid);
1755 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1759 $fields = ['pending' => false];
1761 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1762 if ($contact['rel'] == Contact::FOLLOWER) {
1763 $fields['rel'] = Contact::FRIEND;
1766 $condition = ['id' => $cid];
1767 DBA::update('contact', $fields, $condition);
1768 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1772 * @brief Undo activity like "like" or "dislike"
1774 * @param array $activity
1776 private static function undoActivity($activity)
1778 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
1779 if (empty($activity_url)) {
1783 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1784 if (empty($actor)) {
1788 $author_id = Contact::getIdForURL($actor);
1789 if (empty($author_id)) {
1793 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1797 * @brief Activity to remove a follower
1799 * @param array $activity
1801 private static function undoFollowUser($activity)
1803 $object = JsonLD::fetchElement($activity, 'object', 'object');
1804 $uid = self::getUserOfProfile($object);
1809 $owner = User::getOwnerDataById($uid);
1811 $cid = Contact::getIdForURL($activity['owner'], $uid);
1813 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1817 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1818 if (!DBA::isResult($contact)) {
1822 Contact::removeFollower($owner, $contact);
1823 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);