3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\BaseObject;
8 use Friendica\Content\Feature;
9 use Friendica\Database\DBA;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
13 use Friendica\Util\HTTPSignature;
14 use Friendica\Core\Protocol;
15 use Friendica\Model\Conversation;
16 use Friendica\Model\Contact;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Item;
19 use Friendica\Model\Term;
20 use Friendica\Model\User;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Content\Text\Plaintext;
24 use Friendica\Util\JsonLD;
25 use Friendica\Util\LDSignature;
26 use Friendica\Model\Profile;
27 use Friendica\Object\Image;
28 use Friendica\Protocol\ActivityPub;
29 use Friendica\Core\Cache;
30 use Friendica\Util\Map;
31 use Friendica\Util\Network;
33 require_once 'include/api.php';
34 require_once 'mod/share.php';
37 * @brief ActivityPub Transmitter Protocol class
45 * collects the lost of followers of the given owner
47 * @param array $owner Owner array
48 * @param integer $page Page number
50 * @return array of owners
51 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
53 public static function getFollowers($owner, $page = null)
55 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
56 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
57 $count = DBA::count('contact', $condition);
59 $data = ['@context' => ActivityPub::CONTEXT];
60 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
61 $data['type'] = 'OrderedCollection';
62 $data['totalItems'] = $count;
64 // When we hide our friends we will only show the pure number but don't allow more.
65 $profile = Profile::getByUID($owner['uid']);
66 if (!empty($profile['hide-friends'])) {
71 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
75 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
76 while ($contact = DBA::fetch($contacts)) {
77 $list[] = $contact['url'];
81 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
84 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
86 $data['orderedItems'] = $list;
93 * Create list of following contacts
95 * @param array $owner Owner array
96 * @param integer $page Page numbe
98 * @return array of following contacts
99 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
101 public static function getFollowing($owner, $page = null)
103 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
104 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
105 $count = DBA::count('contact', $condition);
107 $data = ['@context' => ActivityPub::CONTEXT];
108 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
109 $data['type'] = 'OrderedCollection';
110 $data['totalItems'] = $count;
112 // When we hide our friends we will only show the pure number but don't allow more.
113 $profile = Profile::getByUID($owner['uid']);
114 if (!empty($profile['hide-friends'])) {
119 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
123 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
124 while ($contact = DBA::fetch($contacts)) {
125 $list[] = $contact['url'];
129 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
132 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
134 $data['orderedItems'] = $list;
141 * Public posts for the given owner
143 * @param array $owner Owner array
144 * @param integer $page Page numbe
146 * @return array of posts
147 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
148 * @throws \ImagickException
150 public static function getOutbox($owner, $page = null)
152 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
154 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
155 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
156 'deleted' => false, 'visible' => true, 'moderated' => false];
157 $count = DBA::count('item', $condition);
159 $data = ['@context' => ActivityPub::CONTEXT];
160 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
161 $data['type'] = 'OrderedCollection';
162 $data['totalItems'] = $count;
165 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
169 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
171 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
172 while ($item = Item::fetch($items)) {
173 $object = self::createObjectFromItemID($item['id']);
174 unset($object['@context']);
179 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
182 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
184 $data['orderedItems'] = $list;
191 * Return the ActivityPub profile of the given user
193 * @param integer $uid User ID
194 * @return array with profile data
195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
197 public static function getProfile($uid)
199 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
200 'account_removed' => false, 'verified' => true];
201 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
202 $user = DBA::selectFirst('user', $fields, $condition);
203 if (!DBA::isResult($user)) {
207 $fields = ['locality', 'region', 'country-name'];
208 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
209 if (!DBA::isResult($profile)) {
213 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
214 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
215 if (!DBA::isResult($contact)) {
219 // On old installations and never changed contacts this might not be filled
220 if (empty($contact['avatar'])) {
221 $contact['avatar'] = $contact['photo'];
224 $data = ['@context' => ActivityPub::CONTEXT];
225 $data['id'] = $contact['url'];
226 $data['diaspora:guid'] = $user['guid'];
227 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
228 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
229 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
230 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
231 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
232 $data['preferredUsername'] = $user['nickname'];
233 $data['name'] = $contact['name'];
234 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
235 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
236 $data['summary'] = $contact['about'];
237 $data['url'] = $contact['url'];
238 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
239 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
240 'owner' => $contact['url'],
241 'publicKeyPem' => $user['pubkey']];
242 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
243 $data['icon'] = ['type' => 'Image',
244 'url' => $contact['avatar']];
246 // tags: https://kitty.town/@inmysocks/100656097926961126.json
251 * @param string $username
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 public static function getDeletedUser($username)
258 '@context' => ActivityPub::CONTEXT,
259 'id' => System::baseUrl() . '/profile/' . $username,
260 'type' => 'Tombstone',
261 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
262 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
263 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
268 * Returns an array with permissions of a given item array
272 * @return array with permissions
273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
274 * @throws \ImagickException
276 private static function fetchPermissionBlockFromConversation($item)
278 if (empty($item['thr-parent'])) {
282 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
283 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
284 if (!DBA::isResult($conversation)) {
288 $activity = json_decode($conversation['source'], true);
290 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
291 $profile = APContact::getByURL($actor);
293 $item_profile = APContact::getByURL($item['author-link']);
294 $exclude[] = $item['author-link'];
296 if ($item['gravity'] == GRAVITY_PARENT) {
297 $exclude[] = $item['owner-link'];
300 $permissions['to'][] = $actor;
302 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
303 if (empty($activity[$element])) {
306 if (is_string($activity[$element])) {
307 $activity[$element] = [$activity[$element]];
310 foreach ($activity[$element] as $receiver) {
311 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
312 $permissions[$element][] = $item_profile['followers'];
313 } elseif (!in_array($receiver, $exclude)) {
314 $permissions[$element][] = $receiver;
322 * Creates an array of permissions from an item thread
324 * @param array $item Item array
325 * @param boolean $blindcopy addressing via "bcc" or "cc"?
326 * @param integer $last_id Last item id for adding receivers
327 * @param boolean $forum_mode "true" means that we are sending content to a forum
329 * @return array with permission data
330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
331 * @throws \ImagickException
333 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
336 $last_id = $item['id'];
341 // Check if we should always deliver our stuff via BCC
342 if (!empty($item['uid'])) {
343 $profile = Profile::getByUID($item['uid']);
344 if (!empty($profile)) {
345 $always_bcc = $profile['hide-friends'];
349 if (Config::get('debug', 'total_ap_delivery')) {
350 // Will be activated in a later step
351 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
353 // For now only send to these contacts:
354 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
357 $data = ['to' => [], 'cc' => [], 'bcc' => []];
359 if ($item['gravity'] == GRAVITY_PARENT) {
360 $actor_profile = APContact::getByURL($item['owner-link']);
362 $actor_profile = APContact::getByURL($item['author-link']);
365 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
367 if (!$item['private']) {
368 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
370 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
372 foreach ($terms as $term) {
373 $profile = APContact::getByURL($term['url'], false);
374 if (!empty($profile)) {
375 $data['to'][] = $profile['url'];
379 $receiver_list = Item::enumeratePermissions($item);
381 foreach ($terms as $term) {
382 $cid = Contact::getIdForURL($term['url'], $item['uid']);
383 if (!empty($cid) && in_array($cid, $receiver_list)) {
384 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
385 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
386 $data['to'][] = $profile['url'];
391 foreach ($receiver_list as $receiver) {
392 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
393 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
394 if ($contact['hidden'] || $always_bcc) {
395 $data['bcc'][] = $profile['url'];
397 $data['cc'][] = $profile['url'];
403 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
404 while ($parent = Item::fetch($parents)) {
405 if ($parent['gravity'] == GRAVITY_PARENT) {
406 $profile = APContact::getByURL($parent['owner-link'], false);
407 if (!empty($profile)) {
408 if ($item['gravity'] != GRAVITY_PARENT) {
409 // Comments to forums are directed to the forum
410 // But comments to forums aren't directed to the followers collection
411 if ($profile['type'] == 'Group') {
412 $data['to'][] = $profile['url'];
414 $data['cc'][] = $profile['url'];
415 if (!$item['private']) {
416 $data['cc'][] = $actor_profile['followers'];
420 // Public thread parent post always are directed to the followes
421 if (!$item['private'] && !$forum_mode) {
422 $data['cc'][] = $actor_profile['followers'];
428 // Don't include data from future posts
429 if ($parent['id'] >= $last_id) {
433 $profile = APContact::getByURL($parent['author-link'], false);
434 if (!empty($profile)) {
435 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
436 $data['to'][] = $profile['url'];
438 $data['cc'][] = $profile['url'];
442 DBA::close($parents);
444 $data['to'] = array_unique($data['to']);
445 $data['cc'] = array_unique($data['cc']);
446 $data['bcc'] = array_unique($data['bcc']);
448 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
449 unset($data['to'][$key]);
452 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
453 unset($data['cc'][$key]);
456 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
457 unset($data['bcc'][$key]);
460 foreach ($data['to'] as $to) {
461 if (($key = array_search($to, $data['cc'])) !== false) {
462 unset($data['cc'][$key]);
465 if (($key = array_search($to, $data['bcc'])) !== false) {
466 unset($data['bcc'][$key]);
470 foreach ($data['cc'] as $cc) {
471 if (($key = array_search($cc, $data['bcc'])) !== false) {
472 unset($data['bcc'][$key]);
476 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
479 unset($receivers['bcc']);
486 * Check if an inbox is archived
488 * @param string $url Inbox url
490 * @return boolean "true" if inbox is archived
492 private static function archivedInbox($url)
494 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
498 * Fetches a list of inboxes of followers of a given user
500 * @param integer $uid User ID
501 * @param boolean $personal fetch personal inboxes
503 * @return array of follower inboxes
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
505 * @throws \ImagickException
507 public static function fetchTargetInboxesforUser($uid, $personal = false)
511 if (Config::get('debug', 'total_ap_delivery')) {
512 // Will be activated in a later step
513 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
515 // For now only send to these contacts:
516 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
519 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
522 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
525 $contacts = DBA::select('contact', ['url'], $condition);
526 while ($contact = DBA::fetch($contacts)) {
527 if (Network::isUrlBlocked($contact['url'])) {
531 $profile = APContact::getByURL($contact['url'], false);
532 if (!empty($profile)) {
533 if (empty($profile['sharedinbox']) || $personal) {
534 $target = $profile['inbox'];
536 $target = $profile['sharedinbox'];
538 if (!self::archivedInbox($target)) {
539 $inboxes[$target] = $target;
543 DBA::close($contacts);
549 * Fetches an array of inboxes for the given item and user
551 * @param array $item Item array
552 * @param integer $uid User ID
553 * @param boolean $personal fetch personal inboxes
554 * @param integer $last_id Last item id for adding receivers
555 * @param boolean $forum_mode "true" means that we are sending content to a forum
556 * @return array with inboxes
557 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
558 * @throws \ImagickException
560 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
562 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
563 if (empty($permissions)) {
569 if ($item['gravity'] == GRAVITY_ACTIVITY) {
570 $item_profile = APContact::getByURL($item['author-link'], false);
572 $item_profile = APContact::getByURL($item['owner-link'], false);
575 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
576 if (empty($permissions[$element])) {
580 $blindcopy = in_array($element, ['bto', 'bcc']);
582 foreach ($permissions[$element] as $receiver) {
583 if (Network::isUrlBlocked($receiver)) {
587 if ($receiver == $item_profile['followers']) {
588 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
590 $profile = APContact::getByURL($receiver, false);
591 if (!empty($profile)) {
592 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
593 $target = $profile['inbox'];
595 $target = $profile['sharedinbox'];
597 if (!self::archivedInbox($target)) {
598 $inboxes[$target] = $target;
609 * Returns the activity type of a given item
613 * @return string with activity type
614 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
615 * @throws \ImagickException
617 private static function getTypeOfItem($item)
621 // Only check for a reshare, if it is a real reshare and no quoted reshare
622 if (strpos($item['body'], "[share") === 0) {
623 $announce = api_share_as_retweet($item);
624 $reshared = !empty($announce['plink']);
629 } elseif ($item['verb'] == ACTIVITY_POST) {
630 if ($item['created'] == $item['edited']) {
635 } elseif ($item['verb'] == ACTIVITY_LIKE) {
637 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
639 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
641 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
643 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
644 $type = 'TentativeAccept';
645 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
655 * Creates the activity or fetches it from the cache
657 * @param integer $item_id
658 * @param boolean $force Force new cache entry
660 * @return array with the activity
663 public static function createCachedActivityFromItem($item_id, $force = false)
665 $cachekey = 'APDelivery:createActivity:' . $item_id;
668 $data = Cache::get($cachekey);
669 if (!is_null($data)) {
674 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
676 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
681 * Creates an activity array for a given item id
683 * @param integer $item_id
684 * @param boolean $object_mode Is the activity item is used inside another object?
686 * @return array of activity
689 public static function createActivityFromItem($item_id, $object_mode = false)
691 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
693 if (!DBA::isResult($item)) {
697 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
698 $owner = User::getOwnerDataById($item['uid']);
699 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
702 // Disguise forum posts as reshares. Will later be converted to a real announce
703 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
704 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
709 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
710 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
711 if (DBA::isResult($conversation)) {
712 $data = json_decode($conversation['source']);
718 $type = self::getTypeOfItem($item);
722 $data = ['@context' => ActivityPub::CONTEXT];
724 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
726 } elseif ($item['deleted']) {
733 $data['id'] = $item['uri'] . '#' . $type;
734 $data['type'] = $type;
736 if (Item::isForumPost($item) && ($type != 'Announce')) {
737 $data['actor'] = $item['author-link'];
739 $data['actor'] = $item['owner-link'];
742 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
744 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
746 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
748 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
749 $data['object'] = self::createNote($item);
750 } elseif ($data['type'] == 'Announce') {
751 $data = self::createAnnounce($item, $data);
752 } elseif ($data['type'] == 'Follow') {
753 $data['object'] = $item['parent-uri'];
754 } elseif ($data['type'] == 'Undo') {
755 $data['object'] = self::createActivityFromItem($item_id, true);
757 $data['diaspora:guid'] = $item['guid'];
758 if (!empty($item['signed_text'])) {
759 $data['diaspora:like'] = $item['signed_text'];
761 $data['object'] = $item['thr-parent'];
764 if (!empty($item['contact-uid'])) {
765 $uid = $item['contact-uid'];
770 $owner = User::getOwnerDataById($uid);
772 if (!$object_mode && !empty($owner)) {
773 return LDSignature::sign($data, $owner);
778 /// @todo Create "conversation" entry
782 * Creates an object array for a given item id
784 * @param integer $item_id
786 * @return array with the object data
787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
788 * @throws \ImagickException
790 public static function createObjectFromItemID($item_id)
792 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
794 if (!DBA::isResult($item)) {
798 $data = ['@context' => ActivityPub::CONTEXT];
799 $data = array_merge($data, self::createNote($item));
805 * Creates a location entry for a given item array
809 * @return array with location array
811 private static function createLocation($item)
813 $location = ['type' => 'Place'];
815 if (!empty($item['location'])) {
816 $location['name'] = $item['location'];
821 if (empty($item['coord'])) {
822 $coord = Map::getCoordinates($item['location']);
824 $coords = explode(' ', $item['coord']);
825 if (count($coords) == 2) {
826 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
830 if (!empty($coord['lat']) && !empty($coord['lon'])) {
831 $location['latitude'] = $coord['lat'];
832 $location['longitude'] = $coord['lon'];
839 * Returns a tag array for a given item array
843 * @return array of tags
844 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
846 private static function createTagList($item)
850 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
851 foreach ($terms as $term) {
852 if ($term['type'] == Term::HASHTAG) {
853 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
854 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
855 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
856 $contact = Contact::getDetailsByURL($term['url']);
857 if (!empty($contact['addr'])) {
858 $mention = '@' . $contact['addr'];
860 $mention = '@' . $term['url'];
863 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
870 * Adds attachment data to the JSON document
872 * @param array $item Data of the item that is to be posted
873 * @param string $type Object type
875 * @return array with attachment data
876 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
878 private static function createAttachmentList($item, $type)
882 $arr = explode('[/attach],', $item['attach']);
884 foreach ($arr as $r) {
886 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
888 $attributes = ['type' => 'Document',
889 'mediaType' => $matches[3],
890 'url' => $matches[1],
893 if (trim($matches[4]) != '') {
894 $attributes['name'] = trim($matches[4]);
897 $attachments[] = $attributes;
902 if ($type != 'Note') {
906 // Simplify image codes
907 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
909 // Grab all pictures and create attachments out of them
910 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
911 foreach ($pictures[1] as $picture) {
912 $imgdata = Image::getInfoFromURL($picture);
914 $attachments[] = ['type' => 'Document',
915 'mediaType' => $imgdata['mime'],
926 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
928 * @param array $match Matching values for the callback
929 * @return string Replaced mention
930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932 private static function mentionCallback($match)
934 if (empty($match[1])) {
938 $data = Contact::getDetailsByURL($match[1]);
939 if (empty($data['nick'])) {
943 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
947 * Remove image elements and replaces them with links to the image
949 * @param string $body
951 * @return string with replaced elements
953 private static function removePictures($body)
955 // Simplify image codes
956 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
958 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
959 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
965 * Fetches the "context" value for a givem item array from the "conversation" table
969 * @return string with context url
972 private static function fetchContextURLForItem($item)
974 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
975 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
976 $context_uri = $conversation['conversation-href'];
977 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
978 $context_uri = $conversation['conversation-uri'];
980 $context_uri = $item['parent-uri'] . '#context';
986 * Returns if the post contains sensitive content ("nsfw")
988 * @param integer $item_id
993 private static function isSensitive($item_id)
995 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
996 return DBA::exists('term', $condition);
1000 * Creates event data
1002 * @param array $item
1004 * @return array with the event data
1005 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1007 public static function createEvent($item)
1010 $event['name'] = $item['event-summary'];
1011 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
1012 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1014 if (!$item['event-nofinish']) {
1015 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1018 if (!empty($item['event-location'])) {
1019 $item['location'] = $item['event-location'];
1020 $event['location'] = self::createLocation($item);
1027 * Creates a note/article object array
1029 * @param array $item
1031 * @return array with the object data
1032 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1033 * @throws \ImagickException
1035 public static function createNote($item)
1037 if ($item['event-type'] == 'event') {
1039 } elseif (!empty($item['title'])) {
1045 if ($item['deleted']) {
1046 $type = 'Tombstone';
1050 $data['id'] = $item['uri'];
1051 $data['type'] = $type;
1053 if ($item['deleted']) {
1057 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1059 if ($item['uri'] != $item['thr-parent']) {
1060 $data['inReplyTo'] = $item['thr-parent'];
1062 $data['inReplyTo'] = null;
1065 $data['diaspora:guid'] = $item['guid'];
1066 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1068 if ($item['created'] != $item['edited']) {
1069 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1072 $data['url'] = $item['plink'];
1073 $data['attributedTo'] = $item['author-link'];
1074 $data['sensitive'] = self::isSensitive($item['id']);
1075 $data['context'] = self::fetchContextURLForItem($item);
1077 if (!empty($item['title'])) {
1078 $data['name'] = BBCode::toPlaintext($item['title'], false);
1081 $permission_block = self::createPermissionBlockForItem($item, false);
1083 $body = $item['body'];
1085 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1086 $body = self::prependMentions($body, $permission_block);
1089 if ($type == 'Note') {
1090 $body = self::removePictures($body);
1091 } elseif (($type == 'Article') && empty($data['summary'])) {
1092 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1095 if ($type == 'Event') {
1096 $data = array_merge($data, self::createEvent($item));
1098 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1099 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1101 $data['content'] = BBCode::convert($body, false, 7);
1104 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1106 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1107 $data['diaspora:comment'] = $item['signed_text'];
1110 $data['attachment'] = self::createAttachmentList($item, $type);
1111 $data['tag'] = self::createTagList($item);
1113 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1114 $data['location'] = self::createLocation($item);
1117 if (!empty($item['app'])) {
1118 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1121 $data = array_merge($data, $permission_block);
1127 * Creates an announce object entry
1129 * @param array $item
1130 * @param array $data activity data
1132 * @return array with activity data
1133 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1134 * @throws \ImagickException
1136 private static function createAnnounce($item, $data)
1138 $announce = api_share_as_retweet($item);
1139 if (empty($announce['plink'])) {
1140 $data['type'] = 'Create';
1141 $data['object'] = self::createNote($item);
1145 // Fetch the original id of the object
1146 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1147 if (!empty($activity)) {
1148 $ldactivity = JsonLD::compact($activity);
1149 $id = JsonLD::fetchElement($ldactivity, '@id');
1151 $data['object'] = $id;
1156 $data['type'] = 'Create';
1157 $data['object'] = self::createNote($item);
1162 * Creates an activity id for a given contact id
1164 * @param integer $cid Contact ID of target
1166 * @return bool|string activity id
1168 public static function activityIDFromContact($cid)
1170 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1171 if (!DBA::isResult($contact)) {
1175 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1176 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1177 return System::baseUrl() . '/activity/' . $uuid;
1181 * Transmits a contact suggestion to a given inbox
1183 * @param integer $uid User ID
1184 * @param string $inbox Target inbox
1185 * @param integer $suggestion_id Suggestion ID
1187 * @return boolean was the transmission successful?
1188 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1190 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1192 $owner = User::getOwnerDataById($uid);
1194 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1196 $data = ['@context' => ActivityPub::CONTEXT,
1197 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1198 'type' => 'Announce',
1199 'actor' => $owner['url'],
1200 'object' => $suggestion['url'],
1201 'content' => $suggestion['note'],
1202 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1203 'to' => [ActivityPub::PUBLIC_COLLECTION],
1206 $signed = LDSignature::sign($data, $owner);
1208 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1209 return HTTPSignature::transmit($signed, $inbox, $uid);
1213 * Transmits a profile relocation to a given inbox
1215 * @param integer $uid User ID
1216 * @param string $inbox Target inbox
1218 * @return boolean was the transmission successful?
1219 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1221 public static function sendProfileRelocation($uid, $inbox)
1223 $owner = User::getOwnerDataById($uid);
1225 $data = ['@context' => ActivityPub::CONTEXT,
1226 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1227 'type' => 'dfrn:relocate',
1228 'actor' => $owner['url'],
1229 'object' => $owner['url'],
1230 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1231 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1232 'to' => [ActivityPub::PUBLIC_COLLECTION],
1235 $signed = LDSignature::sign($data, $owner);
1237 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1238 return HTTPSignature::transmit($signed, $inbox, $uid);
1242 * Transmits a profile deletion to a given inbox
1244 * @param integer $uid User ID
1245 * @param string $inbox Target inbox
1247 * @return boolean was the transmission successful?
1248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1250 public static function sendProfileDeletion($uid, $inbox)
1252 $owner = User::getOwnerDataById($uid);
1254 if (empty($owner)) {
1255 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1259 if (empty($owner['uprvkey'])) {
1260 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1264 $data = ['@context' => ActivityPub::CONTEXT,
1265 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1267 'actor' => $owner['url'],
1268 'object' => $owner['url'],
1269 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1270 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1271 'to' => [ActivityPub::PUBLIC_COLLECTION],
1274 $signed = LDSignature::sign($data, $owner);
1276 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1277 return HTTPSignature::transmit($signed, $inbox, $uid);
1281 * Transmits a profile change to a given inbox
1283 * @param integer $uid User ID
1284 * @param string $inbox Target inbox
1286 * @return boolean was the transmission successful?
1287 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1288 * @throws \ImagickException
1290 public static function sendProfileUpdate($uid, $inbox)
1292 $owner = User::getOwnerDataById($uid);
1293 $profile = APContact::getByURL($owner['url']);
1295 $data = ['@context' => ActivityPub::CONTEXT,
1296 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1298 'actor' => $owner['url'],
1299 'object' => self::getProfile($uid),
1300 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1301 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1302 'to' => [$profile['followers']],
1305 $signed = LDSignature::sign($data, $owner);
1307 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1308 return HTTPSignature::transmit($signed, $inbox, $uid);
1312 * Transmits a given activity to a target
1314 * @param string $activity Type name
1315 * @param string $target Target profile
1316 * @param integer $uid User ID
1318 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1319 * @throws \ImagickException
1320 * @throws \Exception
1322 public static function sendActivity($activity, $target, $uid, $id = '')
1324 $profile = APContact::getByURL($target);
1326 $owner = User::getOwnerDataById($uid);
1329 $id = System::baseUrl() . '/activity/' . System::createGUID();
1332 $data = ['@context' => ActivityPub::CONTEXT,
1334 'type' => $activity,
1335 'actor' => $owner['url'],
1336 'object' => $profile['url'],
1337 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1338 'to' => [$profile['url']]];
1340 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1342 $signed = LDSignature::sign($data, $owner);
1343 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1347 * Transmits a "follow object" activity to a target
1348 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1350 * @param string $object Object URL
1351 * @param string $target Target profile
1352 * @param integer $uid User ID
1354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1355 * @throws \ImagickException
1356 * @throws \Exception
1358 public static function sendFollowObject($object, $target, $uid = 0)
1360 $profile = APContact::getByURL($target);
1363 // Fetch the list of administrators
1364 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1366 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1367 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1368 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1369 $uid = $first_user['uid'];
1372 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1373 'author-id' => Contact::getPublicIdByUserId($uid)];
1374 if (Item::exists($condition)) {
1375 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1379 $owner = User::getOwnerDataById($uid);
1381 $data = ['@context' => ActivityPub::CONTEXT,
1382 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1384 'actor' => $owner['url'],
1385 'object' => $object,
1386 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1387 'to' => [$profile['url']]];
1389 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1391 $signed = LDSignature::sign($data, $owner);
1392 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1396 * Transmit a message that the contact request had been accepted
1398 * @param string $target Target profile
1400 * @param integer $uid User ID
1401 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1402 * @throws \ImagickException
1404 public static function sendContactAccept($target, $id, $uid)
1406 $profile = APContact::getByURL($target);
1408 $owner = User::getOwnerDataById($uid);
1409 $data = ['@context' => ActivityPub::CONTEXT,
1410 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1412 'actor' => $owner['url'],
1413 'object' => ['id' => $id, 'type' => 'Follow',
1414 'actor' => $profile['url'],
1415 'object' => $owner['url']],
1416 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1417 'to' => [$profile['url']]];
1419 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1421 $signed = LDSignature::sign($data, $owner);
1422 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1426 * Reject a contact request or terminates the contact relation
1428 * @param string $target Target profile
1430 * @param integer $uid User ID
1431 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1432 * @throws \ImagickException
1434 public static function sendContactReject($target, $id, $uid)
1436 $profile = APContact::getByURL($target);
1438 $owner = User::getOwnerDataById($uid);
1439 $data = ['@context' => ActivityPub::CONTEXT,
1440 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1442 'actor' => $owner['url'],
1443 'object' => ['id' => $id, 'type' => 'Follow',
1444 'actor' => $profile['url'],
1445 'object' => $owner['url']],
1446 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1447 'to' => [$profile['url']]];
1449 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1451 $signed = LDSignature::sign($data, $owner);
1452 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1456 * Transmits a message that we don't want to follow this contact anymore
1458 * @param string $target Target profile
1459 * @param integer $uid User ID
1460 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1461 * @throws \ImagickException
1462 * @throws \Exception
1464 public static function sendContactUndo($target, $cid, $uid)
1466 $profile = APContact::getByURL($target);
1468 $object_id = self::activityIDFromContact($cid);
1469 if (empty($object_id)) {
1473 $id = System::baseUrl() . '/activity/' . System::createGUID();
1475 $owner = User::getOwnerDataById($uid);
1476 $data = ['@context' => ActivityPub::CONTEXT,
1479 'actor' => $owner['url'],
1480 'object' => ['id' => $object_id, 'type' => 'Follow',
1481 'actor' => $owner['url'],
1482 'object' => $profile['url']],
1483 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1484 'to' => [$profile['url']]];
1486 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1488 $signed = LDSignature::sign($data, $owner);
1489 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1492 private static function prependMentions($body, array $permission_block)
1494 if (Config::get('system', 'disable_implicit_mentions')) {
1500 foreach ($permission_block['to'] as $profile_url) {
1501 $profile = Contact::getDetailsByURL($profile_url);
1502 if (!empty($profile['addr'])
1503 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1504 && !strstr($body, $profile['addr'])
1505 && !strstr($body, $profile_url)
1507 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1511 $mentions[] = $body;
1513 return implode(' ', $mentions);