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\Util\JsonLD;
24 use Friendica\Util\LDSignature;
25 use Friendica\Model\Profile;
26 use Friendica\Object\Image;
27 use Friendica\Protocol\ActivityPub;
28 use Friendica\Core\Cache;
29 use Friendica\Util\Map;
30 use Friendica\Util\Network;
32 require_once 'include/api.php';
33 require_once 'mod/share.php';
36 * @brief ActivityPub Transmitter Protocol class
44 * collects the lost of followers of the given owner
46 * @param array $owner Owner array
47 * @param integer $page Page number
49 * @return array of owners
50 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
52 public static function getFollowers($owner, $page = null)
54 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
55 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
56 $count = DBA::count('contact', $condition);
58 $data = ['@context' => ActivityPub::CONTEXT];
59 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
60 $data['type'] = 'OrderedCollection';
61 $data['totalItems'] = $count;
63 // When we hide our friends we will only show the pure number but don't allow more.
64 $profile = Profile::getByUID($owner['uid']);
65 if (!empty($profile['hide-friends'])) {
70 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
74 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
75 while ($contact = DBA::fetch($contacts)) {
76 $list[] = $contact['url'];
80 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
83 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
85 $data['orderedItems'] = $list;
92 * Create list of following contacts
94 * @param array $owner Owner array
95 * @param integer $page Page numbe
97 * @return array of following contacts
98 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
100 public static function getFollowing($owner, $page = null)
102 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
103 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
104 $count = DBA::count('contact', $condition);
106 $data = ['@context' => ActivityPub::CONTEXT];
107 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
108 $data['type'] = 'OrderedCollection';
109 $data['totalItems'] = $count;
111 // When we hide our friends we will only show the pure number but don't allow more.
112 $profile = Profile::getByUID($owner['uid']);
113 if (!empty($profile['hide-friends'])) {
118 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
122 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
123 while ($contact = DBA::fetch($contacts)) {
124 $list[] = $contact['url'];
128 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
131 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
133 $data['orderedItems'] = $list;
140 * Public posts for the given owner
142 * @param array $owner Owner array
143 * @param integer $page Page numbe
145 * @return array of posts
146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
147 * @throws \ImagickException
149 public static function getOutbox($owner, $page = null)
151 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
153 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
154 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
155 'deleted' => false, 'visible' => true, 'moderated' => false];
156 $count = DBA::count('item', $condition);
158 $data = ['@context' => ActivityPub::CONTEXT];
159 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
160 $data['type'] = 'OrderedCollection';
161 $data['totalItems'] = $count;
164 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
168 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
170 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
171 while ($item = Item::fetch($items)) {
172 $object = self::createObjectFromItemID($item['id']);
173 unset($object['@context']);
178 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
181 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
183 $data['orderedItems'] = $list;
190 * Return the ActivityPub profile of the given user
192 * @param integer $uid User ID
193 * @return array with profile data
194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196 public static function getProfile($uid)
198 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
199 'account_removed' => false, 'verified' => true];
200 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
201 $user = DBA::selectFirst('user', $fields, $condition);
202 if (!DBA::isResult($user)) {
206 $fields = ['locality', 'region', 'country-name'];
207 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
208 if (!DBA::isResult($profile)) {
212 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
213 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
214 if (!DBA::isResult($contact)) {
218 // On old installations and never changed contacts this might not be filled
219 if (empty($contact['avatar'])) {
220 $contact['avatar'] = $contact['photo'];
223 $data = ['@context' => ActivityPub::CONTEXT];
224 $data['id'] = $contact['url'];
225 $data['diaspora:guid'] = $user['guid'];
226 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
227 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
228 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
229 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
230 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
231 $data['preferredUsername'] = $user['nickname'];
232 $data['name'] = $contact['name'];
233 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
234 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
235 $data['summary'] = $contact['about'];
236 $data['url'] = $contact['url'];
237 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
238 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
239 'owner' => $contact['url'],
240 'publicKeyPem' => $user['pubkey']];
241 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
242 $data['icon'] = ['type' => 'Image',
243 'url' => $contact['avatar']];
245 // tags: https://kitty.town/@inmysocks/100656097926961126.json
250 * Returns an array with permissions of a given item array
254 * @return array with permissions
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 * @throws \ImagickException
258 private static function fetchPermissionBlockFromConversation($item)
260 if (empty($item['thr-parent'])) {
264 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
265 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
266 if (!DBA::isResult($conversation)) {
270 $activity = json_decode($conversation['source'], true);
272 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
273 $profile = APContact::getByURL($actor);
275 $item_profile = APContact::getByURL($item['author-link']);
276 $exclude[] = $item['author-link'];
278 if ($item['gravity'] == GRAVITY_PARENT) {
279 $exclude[] = $item['owner-link'];
282 $permissions['to'][] = $actor;
284 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
285 if (empty($activity[$element])) {
288 if (is_string($activity[$element])) {
289 $activity[$element] = [$activity[$element]];
292 foreach ($activity[$element] as $receiver) {
293 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
294 $permissions[$element][] = $item_profile['followers'];
295 } elseif (!in_array($receiver, $exclude)) {
296 $permissions[$element][] = $receiver;
304 * Creates an array of permissions from an item thread
306 * @param array $item Item array
307 * @param boolean $blindcopy addressing via "bcc" or "cc"?
308 * @param integer $last_id Last item id for adding receivers
309 * @param boolean $forum_mode "true" means that we are sending content to a forum
311 * @return array with permission data
312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
313 * @throws \ImagickException
315 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
318 $last_id = $item['id'];
323 // Check if we should always deliver our stuff via BCC
324 if (!empty($item['uid'])) {
325 $profile = Profile::getByUID($item['uid']);
326 if (!empty($profile)) {
327 $always_bcc = $profile['hide-friends'];
331 if (Config::get('debug', 'total_ap_delivery')) {
332 // Will be activated in a later step
333 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
335 // For now only send to these contacts:
336 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
339 $data = ['to' => [], 'cc' => [], 'bcc' => []];
341 if ($item['gravity'] == GRAVITY_PARENT) {
342 $actor_profile = APContact::getByURL($item['owner-link']);
344 $actor_profile = APContact::getByURL($item['author-link']);
347 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
349 if (!$item['private']) {
350 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
352 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
354 foreach ($terms as $term) {
355 $profile = APContact::getByURL($term['url'], false);
356 if (!empty($profile)) {
357 $data['to'][] = $profile['url'];
361 $receiver_list = Item::enumeratePermissions($item);
363 foreach ($terms as $term) {
364 $cid = Contact::getIdForURL($term['url'], $item['uid']);
365 if (!empty($cid) && in_array($cid, $receiver_list)) {
366 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
367 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
368 $data['to'][] = $profile['url'];
373 foreach ($receiver_list as $receiver) {
374 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
375 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
376 if ($contact['hidden'] || $always_bcc) {
377 $data['bcc'][] = $profile['url'];
379 $data['cc'][] = $profile['url'];
385 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
386 while ($parent = Item::fetch($parents)) {
387 if ($parent['gravity'] == GRAVITY_PARENT) {
388 $profile = APContact::getByURL($parent['owner-link'], false);
389 if (!empty($profile)) {
390 if ($item['gravity'] != GRAVITY_PARENT) {
391 // Comments to forums are directed to the forum
392 // But comments to forums aren't directed to the followers collection
393 if ($profile['type'] == 'Group') {
394 $data['to'][] = $profile['url'];
396 $data['cc'][] = $profile['url'];
397 if (!$item['private']) {
398 $data['cc'][] = $actor_profile['followers'];
402 // Public thread parent post always are directed to the followes
403 if (!$item['private'] && !$forum_mode) {
404 $data['cc'][] = $actor_profile['followers'];
410 // Don't include data from future posts
411 if ($parent['id'] >= $last_id) {
415 $profile = APContact::getByURL($parent['author-link'], false);
416 if (!empty($profile)) {
417 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
418 $data['to'][] = $profile['url'];
420 $data['cc'][] = $profile['url'];
424 DBA::close($parents);
426 $data['to'] = array_unique($data['to']);
427 $data['cc'] = array_unique($data['cc']);
428 $data['bcc'] = array_unique($data['bcc']);
430 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
431 unset($data['to'][$key]);
434 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
435 unset($data['cc'][$key]);
438 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
439 unset($data['bcc'][$key]);
442 foreach ($data['to'] as $to) {
443 if (($key = array_search($to, $data['cc'])) !== false) {
444 unset($data['cc'][$key]);
447 if (($key = array_search($to, $data['bcc'])) !== false) {
448 unset($data['bcc'][$key]);
452 foreach ($data['cc'] as $cc) {
453 if (($key = array_search($cc, $data['bcc'])) !== false) {
454 unset($data['bcc'][$key]);
458 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
461 unset($receivers['bcc']);
468 * Fetches a list of inboxes of followers of a given user
470 * @param integer $uid User ID
471 * @param boolean $personal fetch personal inboxes
473 * @return array of follower inboxes
474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
475 * @throws \ImagickException
477 public static function fetchTargetInboxesforUser($uid, $personal = false)
481 if (Config::get('debug', 'total_ap_delivery')) {
482 // Will be activated in a later step
483 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
485 // For now only send to these contacts:
486 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
489 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
492 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
495 $contacts = DBA::select('contact', ['url'], $condition);
496 while ($contact = DBA::fetch($contacts)) {
497 if (Network::isUrlBlocked($contact['url'])) {
501 $profile = APContact::getByURL($contact['url'], false);
502 if (!empty($profile)) {
503 if (empty($profile['sharedinbox']) || $personal) {
504 $target = $profile['inbox'];
506 $target = $profile['sharedinbox'];
508 $inboxes[$target] = $target;
511 DBA::close($contacts);
517 * Fetches an array of inboxes for the given item and user
519 * @param array $item Item array
520 * @param integer $uid User ID
521 * @param boolean $personal fetch personal inboxes
522 * @param integer $last_id Last item id for adding receivers
523 * @param boolean $forum_mode "true" means that we are sending content to a forum
524 * @return array with inboxes
525 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
526 * @throws \ImagickException
528 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
530 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
531 if (empty($permissions)) {
537 if ($item['gravity'] == GRAVITY_ACTIVITY) {
538 $item_profile = APContact::getByURL($item['author-link'], false);
540 $item_profile = APContact::getByURL($item['owner-link'], false);
543 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
544 if (empty($permissions[$element])) {
548 $blindcopy = in_array($element, ['bto', 'bcc']);
550 foreach ($permissions[$element] as $receiver) {
551 if (Network::isUrlBlocked($receiver)) {
555 if ($receiver == $item_profile['followers']) {
556 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
558 $profile = APContact::getByURL($receiver, false);
559 if (!empty($profile)) {
560 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
561 $target = $profile['inbox'];
563 $target = $profile['sharedinbox'];
565 $inboxes[$target] = $target;
575 * Returns the activity type of a given item
579 * @return string with activity type
580 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
581 * @throws \ImagickException
583 private static function getTypeOfItem($item)
587 // Only check for a reshare, if it is a real reshare and no quoted reshare
588 if (strpos($item['body'], "[share") === 0) {
589 $announce = api_share_as_retweet($item);
590 $reshared = !empty($announce['plink']);
595 } elseif ($item['verb'] == ACTIVITY_POST) {
596 if ($item['created'] == $item['edited']) {
601 } elseif ($item['verb'] == ACTIVITY_LIKE) {
603 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
605 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
607 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
609 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
610 $type = 'TentativeAccept';
611 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
621 * Creates the activity or fetches it from the cache
623 * @param integer $item_id
624 * @param boolean $force Force new cache entry
626 * @return array with the activity
629 public static function createCachedActivityFromItem($item_id, $force = false)
631 $cachekey = 'APDelivery:createActivity:' . $item_id;
634 $data = Cache::get($cachekey);
635 if (!is_null($data)) {
640 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
642 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
647 * Creates an activity array for a given item id
649 * @param integer $item_id
650 * @param boolean $object_mode Is the activity item is used inside another object?
652 * @return array of activity
655 public static function createActivityFromItem($item_id, $object_mode = false)
657 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
659 if (!DBA::isResult($item)) {
663 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
664 $owner = User::getOwnerDataById($item['uid']);
665 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
668 // Disguise forum posts as reshares. Will later be converted to a real announce
669 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
670 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
675 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
676 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
677 if (DBA::isResult($conversation)) {
678 $data = json_decode($conversation['source']);
684 $type = self::getTypeOfItem($item);
688 $data = ['@context' => ActivityPub::CONTEXT];
690 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
692 } elseif ($item['deleted']) {
699 $data['id'] = $item['uri'] . '#' . $type;
700 $data['type'] = $type;
702 if (Item::isForumPost($item) && ($type != 'Announce')) {
703 $data['actor'] = $item['author-link'];
705 $data['actor'] = $item['owner-link'];
708 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
710 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
712 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
714 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
715 $data['object'] = self::createNote($item);
716 } elseif ($data['type'] == 'Announce') {
717 $data = self::createAnnounce($item, $data);
718 } elseif ($data['type'] == 'Follow') {
719 $data['object'] = $item['parent-uri'];
720 } elseif ($data['type'] == 'Undo') {
721 $data['object'] = self::createActivityFromItem($item_id, true);
723 $data['diaspora:guid'] = $item['guid'];
724 if (!empty($item['signed_text'])) {
725 $data['diaspora:like'] = $item['signed_text'];
727 $data['object'] = $item['thr-parent'];
730 if (!empty($item['contact-uid'])) {
731 $uid = $item['contact-uid'];
736 $owner = User::getOwnerDataById($uid);
738 if (!$object_mode && !empty($owner)) {
739 return LDSignature::sign($data, $owner);
744 /// @todo Create "conversation" entry
748 * Creates an object array for a given item id
750 * @param integer $item_id
752 * @return array with the object data
753 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
754 * @throws \ImagickException
756 public static function createObjectFromItemID($item_id)
758 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
760 if (!DBA::isResult($item)) {
764 $data = ['@context' => ActivityPub::CONTEXT];
765 $data = array_merge($data, self::createNote($item));
771 * Creates a location entry for a given item array
775 * @return array with location array
777 private static function createLocation($item)
779 $location = ['type' => 'Place'];
781 if (!empty($item['location'])) {
782 $location['name'] = $item['location'];
787 if (empty($item['coord'])) {
788 $coord = Map::getCoordinates($item['location']);
790 $coords = explode(' ', $item['coord']);
791 if (count($coords) == 2) {
792 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
796 if (!empty($coord['lat']) && !empty($coord['lon'])) {
797 $location['latitude'] = $coord['lat'];
798 $location['longitude'] = $coord['lon'];
805 * Returns a tag array for a given item array
809 * @return array of tags
810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
812 private static function createTagList($item)
816 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
817 foreach ($terms as $term) {
818 if ($term['type'] == Term::HASHTAG) {
819 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
820 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
821 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
822 $contact = Contact::getDetailsByURL($term['url']);
823 if (!empty($contact['addr'])) {
824 $mention = '@' . $contact['addr'];
826 $mention = '@' . $term['url'];
829 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
836 * Adds attachment data to the JSON document
838 * @param array $item Data of the item that is to be posted
839 * @param string $type Object type
841 * @return array with attachment data
842 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
844 private static function createAttachmentList($item, $type)
848 $arr = explode('[/attach],', $item['attach']);
850 foreach ($arr as $r) {
852 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
854 $attributes = ['type' => 'Document',
855 'mediaType' => $matches[3],
856 'url' => $matches[1],
859 if (trim($matches[4]) != '') {
860 $attributes['name'] = trim($matches[4]);
863 $attachments[] = $attributes;
868 if ($type != 'Note') {
872 // Simplify image codes
873 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
875 // Grab all pictures and create attachments out of them
876 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
877 foreach ($pictures[1] as $picture) {
878 $imgdata = Image::getInfoFromURL($picture);
880 $attachments[] = ['type' => 'Document',
881 'mediaType' => $imgdata['mime'],
892 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
894 * @param array $match Matching values for the callback
895 * @return string Replaced mention
896 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
898 private static function mentionCallback($match)
900 if (empty($match[1])) {
904 $data = Contact::getDetailsByURL($match[1]);
905 if (empty($data['nick'])) {
909 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
913 * Remove image elements and replaces them with links to the image
915 * @param string $body
917 * @return string with replaced elements
919 private static function removePictures($body)
921 // Simplify image codes
922 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
924 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
925 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
931 * Fetches the "context" value for a givem item array from the "conversation" table
935 * @return string with context url
938 private static function fetchContextURLForItem($item)
940 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
941 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
942 $context_uri = $conversation['conversation-href'];
943 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
944 $context_uri = $conversation['conversation-uri'];
946 $context_uri = $item['parent-uri'] . '#context';
952 * Returns if the post contains sensitive content ("nsfw")
954 * @param integer $item_id
959 private static function isSensitive($item_id)
961 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
962 return DBA::exists('term', $condition);
970 * @return array with the event data
971 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
973 public static function createEvent($item)
976 $event['name'] = $item['event-summary'];
977 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
978 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
980 if (!$item['event-nofinish']) {
981 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
984 if (!empty($item['event-location'])) {
985 $item['location'] = $item['event-location'];
986 $event['location'] = self::createLocation($item);
993 * Creates a note/article object array
997 * @return array with the object data
998 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
999 * @throws \ImagickException
1001 public static function createNote($item)
1003 if ($item['event-type'] == 'event') {
1005 } elseif (!empty($item['title'])) {
1011 if ($item['deleted']) {
1012 $type = 'Tombstone';
1016 $data['id'] = $item['uri'];
1017 $data['type'] = $type;
1019 if ($item['deleted']) {
1023 $data['summary'] = null; // Ignore by now
1025 if ($item['uri'] != $item['thr-parent']) {
1026 $data['inReplyTo'] = $item['thr-parent'];
1028 $data['inReplyTo'] = null;
1031 $data['diaspora:guid'] = $item['guid'];
1032 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1034 if ($item['created'] != $item['edited']) {
1035 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1038 $data['url'] = $item['plink'];
1039 $data['attributedTo'] = $item['author-link'];
1040 $data['sensitive'] = self::isSensitive($item['id']);
1041 $data['context'] = self::fetchContextURLForItem($item);
1043 if (!empty($item['title'])) {
1044 $data['name'] = BBCode::toPlaintext($item['title'], false);
1047 $permission_block = self::createPermissionBlockForItem($item, false);
1049 $body = $item['body'];
1051 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1052 $body = self::prependMentions($body, $permission_block);
1055 if ($type == 'Note') {
1056 $body = self::removePictures($body);
1059 if ($type == 'Event') {
1060 $data = array_merge($data, self::createEvent($item));
1062 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1063 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1065 $data['content'] = BBCode::convert($body, false, 7);
1068 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1070 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1071 $data['diaspora:comment'] = $item['signed_text'];
1074 $data['attachment'] = self::createAttachmentList($item, $type);
1075 $data['tag'] = self::createTagList($item);
1077 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1078 $data['location'] = self::createLocation($item);
1081 if (!empty($item['app'])) {
1082 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1085 $data = array_merge($data, $permission_block);
1091 * Creates an announce object entry
1093 * @param array $item
1094 * @param array $data activity data
1096 * @return array with activity data
1097 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1098 * @throws \ImagickException
1100 private static function createAnnounce($item, $data)
1102 $announce = api_share_as_retweet($item);
1103 if (empty($announce['plink'])) {
1104 $data['type'] = 'Create';
1105 $data['object'] = self::createNote($item);
1109 // Fetch the original id of the object
1110 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1111 if (!empty($activity)) {
1112 $ldactivity = JsonLD::compact($activity);
1113 $id = JsonLD::fetchElement($ldactivity, '@id');
1115 $data['object'] = $id;
1120 $data['type'] = 'Create';
1121 $data['object'] = self::createNote($item);
1126 * Creates an activity id for a given contact id
1128 * @param integer $cid Contact ID of target
1130 * @return bool|string activity id
1132 public static function activityIDFromContact($cid)
1134 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1135 if (!DBA::isResult($contact)) {
1139 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1140 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1141 return System::baseUrl() . '/activity/' . $uuid;
1145 * Transmits a contact suggestion to a given inbox
1147 * @param integer $uid User ID
1148 * @param string $inbox Target inbox
1149 * @param integer $suggestion_id Suggestion ID
1151 * @return boolean was the transmission successful?
1152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1154 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1156 $owner = User::getOwnerDataById($uid);
1158 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1160 $data = ['@context' => ActivityPub::CONTEXT,
1161 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1162 'type' => 'Announce',
1163 'actor' => $owner['url'],
1164 'object' => $suggestion['url'],
1165 'content' => $suggestion['note'],
1166 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1167 'to' => [ActivityPub::PUBLIC_COLLECTION],
1170 $signed = LDSignature::sign($data, $owner);
1172 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1173 return HTTPSignature::transmit($signed, $inbox, $uid);
1177 * Transmits a profile relocation to a given inbox
1179 * @param integer $uid User ID
1180 * @param string $inbox Target inbox
1182 * @return boolean was the transmission successful?
1183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1185 public static function sendProfileRelocation($uid, $inbox)
1187 $owner = User::getOwnerDataById($uid);
1189 $data = ['@context' => ActivityPub::CONTEXT,
1190 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1191 'type' => 'dfrn:relocate',
1192 'actor' => $owner['url'],
1193 'object' => $owner['url'],
1194 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1195 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1196 'to' => [ActivityPub::PUBLIC_COLLECTION],
1199 $signed = LDSignature::sign($data, $owner);
1201 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1202 return HTTPSignature::transmit($signed, $inbox, $uid);
1206 * Transmits a profile deletion to a given inbox
1208 * @param integer $uid User ID
1209 * @param string $inbox Target inbox
1211 * @return boolean was the transmission successful?
1212 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1214 public static function sendProfileDeletion($uid, $inbox)
1216 $owner = User::getOwnerDataById($uid);
1218 if (empty($owner)) {
1219 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1223 if (empty($owner['uprvkey'])) {
1224 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1228 $data = ['@context' => ActivityPub::CONTEXT,
1229 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1231 'actor' => $owner['url'],
1232 'object' => $owner['url'],
1233 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1234 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1235 'to' => [ActivityPub::PUBLIC_COLLECTION],
1238 $signed = LDSignature::sign($data, $owner);
1240 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1241 return HTTPSignature::transmit($signed, $inbox, $uid);
1245 * Transmits a profile change to a given inbox
1247 * @param integer $uid User ID
1248 * @param string $inbox Target inbox
1250 * @return boolean was the transmission successful?
1251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1252 * @throws \ImagickException
1254 public static function sendProfileUpdate($uid, $inbox)
1256 $owner = User::getOwnerDataById($uid);
1257 $profile = APContact::getByURL($owner['url']);
1259 $data = ['@context' => ActivityPub::CONTEXT,
1260 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1262 'actor' => $owner['url'],
1263 'object' => self::getProfile($uid),
1264 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1265 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1266 'to' => [$profile['followers']],
1269 $signed = LDSignature::sign($data, $owner);
1271 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1272 return HTTPSignature::transmit($signed, $inbox, $uid);
1276 * Transmits a given activity to a target
1278 * @param string $activity Type name
1279 * @param string $target Target profile
1280 * @param integer $uid User ID
1282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1283 * @throws \ImagickException
1284 * @throws \Exception
1286 public static function sendActivity($activity, $target, $uid, $id = '')
1288 $profile = APContact::getByURL($target);
1290 $owner = User::getOwnerDataById($uid);
1293 $id = System::baseUrl() . '/activity/' . System::createGUID();
1296 $data = ['@context' => ActivityPub::CONTEXT,
1298 'type' => $activity,
1299 'actor' => $owner['url'],
1300 'object' => $profile['url'],
1301 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1302 'to' => [$profile['url']]];
1304 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1306 $signed = LDSignature::sign($data, $owner);
1307 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1311 * Transmits a "follow object" activity to a target
1312 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1314 * @param string $object Object URL
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 sendFollowObject($object, $target, $uid = 0)
1324 $profile = APContact::getByURL($target);
1327 // Fetch the list of administrators
1328 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1330 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1331 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1332 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1333 $uid = $first_user['uid'];
1336 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1337 'author-id' => Contact::getPublicIdByUserId($uid)];
1338 if (Item::exists($condition)) {
1339 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1343 $owner = User::getOwnerDataById($uid);
1345 $data = ['@context' => ActivityPub::CONTEXT,
1346 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1348 'actor' => $owner['url'],
1349 'object' => $object,
1350 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1351 'to' => [$profile['url']]];
1353 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1355 $signed = LDSignature::sign($data, $owner);
1356 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1360 * Transmit a message that the contact request had been accepted
1362 * @param string $target Target profile
1364 * @param integer $uid User ID
1365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1366 * @throws \ImagickException
1368 public static function sendContactAccept($target, $id, $uid)
1370 $profile = APContact::getByURL($target);
1372 $owner = User::getOwnerDataById($uid);
1373 $data = ['@context' => ActivityPub::CONTEXT,
1374 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1376 'actor' => $owner['url'],
1377 'object' => ['id' => $id, 'type' => 'Follow',
1378 'actor' => $profile['url'],
1379 'object' => $owner['url']],
1380 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1381 'to' => [$profile['url']]];
1383 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1385 $signed = LDSignature::sign($data, $owner);
1386 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1390 * Reject a contact request or terminates the contact relation
1392 * @param string $target Target profile
1394 * @param integer $uid User ID
1395 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1396 * @throws \ImagickException
1398 public static function sendContactReject($target, $id, $uid)
1400 $profile = APContact::getByURL($target);
1402 $owner = User::getOwnerDataById($uid);
1403 $data = ['@context' => ActivityPub::CONTEXT,
1404 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1406 'actor' => $owner['url'],
1407 'object' => ['id' => $id, 'type' => 'Follow',
1408 'actor' => $profile['url'],
1409 'object' => $owner['url']],
1410 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1411 'to' => [$profile['url']]];
1413 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1415 $signed = LDSignature::sign($data, $owner);
1416 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1420 * Transmits a message that we don't want to follow this contact anymore
1422 * @param string $target Target profile
1423 * @param integer $uid User ID
1424 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1425 * @throws \ImagickException
1426 * @throws \Exception
1428 public static function sendContactUndo($target, $cid, $uid)
1430 $profile = APContact::getByURL($target);
1432 $object_id = self::activityIDFromContact($cid);
1433 if (empty($object_id)) {
1437 $id = System::baseUrl() . '/activity/' . System::createGUID();
1439 $owner = User::getOwnerDataById($uid);
1440 $data = ['@context' => ActivityPub::CONTEXT,
1443 'actor' => $owner['url'],
1444 'object' => ['id' => $object_id, 'type' => 'Follow',
1445 'actor' => $owner['url'],
1446 'object' => $profile['url']],
1447 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1448 'to' => [$profile['url']]];
1450 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1452 $signed = LDSignature::sign($data, $owner);
1453 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1456 private static function prependMentions($body, array $permission_block)
1458 if (Config::get('system', 'disable_implicit_mentions')) {
1464 foreach ($permission_block['to'] as $profile_url) {
1465 $profile = Contact::getDetailsByURL($profile_url);
1466 if (!empty($profile['addr'])
1467 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1468 && !strstr($body, $profile['addr'])
1469 && !strstr($body, $profile_url)
1471 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1475 $mentions[] = $body;
1477 return implode(' ', $mentions);