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 * Returns an array with permissions of a given item array
255 * @return array with permissions
256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
257 * @throws \ImagickException
259 private static function fetchPermissionBlockFromConversation($item)
261 if (empty($item['thr-parent'])) {
265 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
266 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
267 if (!DBA::isResult($conversation)) {
271 $activity = json_decode($conversation['source'], true);
273 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
274 $profile = APContact::getByURL($actor);
276 $item_profile = APContact::getByURL($item['author-link']);
277 $exclude[] = $item['author-link'];
279 if ($item['gravity'] == GRAVITY_PARENT) {
280 $exclude[] = $item['owner-link'];
283 $permissions['to'][] = $actor;
285 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
286 if (empty($activity[$element])) {
289 if (is_string($activity[$element])) {
290 $activity[$element] = [$activity[$element]];
293 foreach ($activity[$element] as $receiver) {
294 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
295 $permissions[$element][] = $item_profile['followers'];
296 } elseif (!in_array($receiver, $exclude)) {
297 $permissions[$element][] = $receiver;
305 * Creates an array of permissions from an item thread
307 * @param array $item Item array
308 * @param boolean $blindcopy addressing via "bcc" or "cc"?
309 * @param integer $last_id Last item id for adding receivers
310 * @param boolean $forum_mode "true" means that we are sending content to a forum
312 * @return array with permission data
313 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
314 * @throws \ImagickException
316 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
319 $last_id = $item['id'];
324 // Check if we should always deliver our stuff via BCC
325 if (!empty($item['uid'])) {
326 $profile = Profile::getByUID($item['uid']);
327 if (!empty($profile)) {
328 $always_bcc = $profile['hide-friends'];
332 if (Config::get('debug', 'total_ap_delivery')) {
333 // Will be activated in a later step
334 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
336 // For now only send to these contacts:
337 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
340 $data = ['to' => [], 'cc' => [], 'bcc' => []];
342 if ($item['gravity'] == GRAVITY_PARENT) {
343 $actor_profile = APContact::getByURL($item['owner-link']);
345 $actor_profile = APContact::getByURL($item['author-link']);
348 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
350 if (!$item['private']) {
351 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
353 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
355 foreach ($terms as $term) {
356 $profile = APContact::getByURL($term['url'], false);
357 if (!empty($profile)) {
358 $data['to'][] = $profile['url'];
362 $receiver_list = Item::enumeratePermissions($item);
364 foreach ($terms as $term) {
365 $cid = Contact::getIdForURL($term['url'], $item['uid']);
366 if (!empty($cid) && in_array($cid, $receiver_list)) {
367 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
368 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
369 $data['to'][] = $profile['url'];
374 foreach ($receiver_list as $receiver) {
375 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
376 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
377 if ($contact['hidden'] || $always_bcc) {
378 $data['bcc'][] = $profile['url'];
380 $data['cc'][] = $profile['url'];
386 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
387 while ($parent = Item::fetch($parents)) {
388 if ($parent['gravity'] == GRAVITY_PARENT) {
389 $profile = APContact::getByURL($parent['owner-link'], false);
390 if (!empty($profile)) {
391 if ($item['gravity'] != GRAVITY_PARENT) {
392 // Comments to forums are directed to the forum
393 // But comments to forums aren't directed to the followers collection
394 if ($profile['type'] == 'Group') {
395 $data['to'][] = $profile['url'];
397 $data['cc'][] = $profile['url'];
398 if (!$item['private']) {
399 $data['cc'][] = $actor_profile['followers'];
403 // Public thread parent post always are directed to the followes
404 if (!$item['private'] && !$forum_mode) {
405 $data['cc'][] = $actor_profile['followers'];
411 // Don't include data from future posts
412 if ($parent['id'] >= $last_id) {
416 $profile = APContact::getByURL($parent['author-link'], false);
417 if (!empty($profile)) {
418 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
419 $data['to'][] = $profile['url'];
421 $data['cc'][] = $profile['url'];
425 DBA::close($parents);
427 $data['to'] = array_unique($data['to']);
428 $data['cc'] = array_unique($data['cc']);
429 $data['bcc'] = array_unique($data['bcc']);
431 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
432 unset($data['to'][$key]);
435 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
436 unset($data['cc'][$key]);
439 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
440 unset($data['bcc'][$key]);
443 foreach ($data['to'] as $to) {
444 if (($key = array_search($to, $data['cc'])) !== false) {
445 unset($data['cc'][$key]);
448 if (($key = array_search($to, $data['bcc'])) !== false) {
449 unset($data['bcc'][$key]);
453 foreach ($data['cc'] as $cc) {
454 if (($key = array_search($cc, $data['bcc'])) !== false) {
455 unset($data['bcc'][$key]);
459 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
462 unset($receivers['bcc']);
469 * Check if an inbox is archived
471 * @param string $url Inbox url
473 * @return boolean "true" if inbox is archived
475 private static function archivedInbox($url)
477 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
481 * Fetches a list of inboxes of followers of a given user
483 * @param integer $uid User ID
484 * @param boolean $personal fetch personal inboxes
486 * @return array of follower inboxes
487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
488 * @throws \ImagickException
490 public static function fetchTargetInboxesforUser($uid, $personal = false)
494 if (Config::get('debug', 'total_ap_delivery')) {
495 // Will be activated in a later step
496 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
498 // For now only send to these contacts:
499 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
502 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
505 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
508 $contacts = DBA::select('contact', ['url'], $condition);
509 while ($contact = DBA::fetch($contacts)) {
510 if (Network::isUrlBlocked($contact['url'])) {
514 $profile = APContact::getByURL($contact['url'], false);
515 if (!empty($profile)) {
516 if (empty($profile['sharedinbox']) || $personal) {
517 $target = $profile['inbox'];
519 $target = $profile['sharedinbox'];
521 if (!self::archivedInbox($target)) {
522 $inboxes[$target] = $target;
526 DBA::close($contacts);
532 * Fetches an array of inboxes for the given item and user
534 * @param array $item Item array
535 * @param integer $uid User ID
536 * @param boolean $personal fetch personal inboxes
537 * @param integer $last_id Last item id for adding receivers
538 * @param boolean $forum_mode "true" means that we are sending content to a forum
539 * @return array with inboxes
540 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
541 * @throws \ImagickException
543 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
545 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
546 if (empty($permissions)) {
552 if ($item['gravity'] == GRAVITY_ACTIVITY) {
553 $item_profile = APContact::getByURL($item['author-link'], false);
555 $item_profile = APContact::getByURL($item['owner-link'], false);
558 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
559 if (empty($permissions[$element])) {
563 $blindcopy = in_array($element, ['bto', 'bcc']);
565 foreach ($permissions[$element] as $receiver) {
566 if (Network::isUrlBlocked($receiver)) {
570 if ($receiver == $item_profile['followers']) {
571 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
573 $profile = APContact::getByURL($receiver, false);
574 if (!empty($profile)) {
575 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
576 $target = $profile['inbox'];
578 $target = $profile['sharedinbox'];
580 if (!self::archivedInbox($target)) {
581 $inboxes[$target] = $target;
592 * Returns the activity type of a given item
596 * @return string with activity type
597 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
598 * @throws \ImagickException
600 private static function getTypeOfItem($item)
604 // Only check for a reshare, if it is a real reshare and no quoted reshare
605 if (strpos($item['body'], "[share") === 0) {
606 $announce = api_share_as_retweet($item);
607 $reshared = !empty($announce['plink']);
612 } elseif ($item['verb'] == ACTIVITY_POST) {
613 if ($item['created'] == $item['edited']) {
618 } elseif ($item['verb'] == ACTIVITY_LIKE) {
620 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
622 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
624 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
626 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
627 $type = 'TentativeAccept';
628 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
638 * Creates the activity or fetches it from the cache
640 * @param integer $item_id
641 * @param boolean $force Force new cache entry
643 * @return array with the activity
646 public static function createCachedActivityFromItem($item_id, $force = false)
648 $cachekey = 'APDelivery:createActivity:' . $item_id;
651 $data = Cache::get($cachekey);
652 if (!is_null($data)) {
657 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
659 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
664 * Creates an activity array for a given item id
666 * @param integer $item_id
667 * @param boolean $object_mode Is the activity item is used inside another object?
669 * @return array of activity
672 public static function createActivityFromItem($item_id, $object_mode = false)
674 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
676 if (!DBA::isResult($item)) {
680 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
681 $owner = User::getOwnerDataById($item['uid']);
682 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
685 // Disguise forum posts as reshares. Will later be converted to a real announce
686 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
687 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
692 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
693 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
694 if (DBA::isResult($conversation)) {
695 $data = json_decode($conversation['source']);
701 $type = self::getTypeOfItem($item);
705 $data = ['@context' => ActivityPub::CONTEXT];
707 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
709 } elseif ($item['deleted']) {
716 $data['id'] = $item['uri'] . '#' . $type;
717 $data['type'] = $type;
719 if (Item::isForumPost($item) && ($type != 'Announce')) {
720 $data['actor'] = $item['author-link'];
722 $data['actor'] = $item['owner-link'];
725 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
727 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
729 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
731 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
732 $data['object'] = self::createNote($item);
733 } elseif ($data['type'] == 'Announce') {
734 $data = self::createAnnounce($item, $data);
735 } elseif ($data['type'] == 'Follow') {
736 $data['object'] = $item['parent-uri'];
737 } elseif ($data['type'] == 'Undo') {
738 $data['object'] = self::createActivityFromItem($item_id, true);
740 $data['diaspora:guid'] = $item['guid'];
741 if (!empty($item['signed_text'])) {
742 $data['diaspora:like'] = $item['signed_text'];
744 $data['object'] = $item['thr-parent'];
747 if (!empty($item['contact-uid'])) {
748 $uid = $item['contact-uid'];
753 $owner = User::getOwnerDataById($uid);
755 if (!$object_mode && !empty($owner)) {
756 return LDSignature::sign($data, $owner);
761 /// @todo Create "conversation" entry
765 * Creates an object array for a given item id
767 * @param integer $item_id
769 * @return array with the object data
770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
771 * @throws \ImagickException
773 public static function createObjectFromItemID($item_id)
775 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
777 if (!DBA::isResult($item)) {
781 $data = ['@context' => ActivityPub::CONTEXT];
782 $data = array_merge($data, self::createNote($item));
788 * Creates a location entry for a given item array
792 * @return array with location array
794 private static function createLocation($item)
796 $location = ['type' => 'Place'];
798 if (!empty($item['location'])) {
799 $location['name'] = $item['location'];
804 if (empty($item['coord'])) {
805 $coord = Map::getCoordinates($item['location']);
807 $coords = explode(' ', $item['coord']);
808 if (count($coords) == 2) {
809 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
813 if (!empty($coord['lat']) && !empty($coord['lon'])) {
814 $location['latitude'] = $coord['lat'];
815 $location['longitude'] = $coord['lon'];
822 * Returns a tag array for a given item array
826 * @return array of tags
827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
829 private static function createTagList($item)
833 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
834 foreach ($terms as $term) {
835 if ($term['type'] == Term::HASHTAG) {
836 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
837 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
838 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
839 $contact = Contact::getDetailsByURL($term['url']);
840 if (!empty($contact['addr'])) {
841 $mention = '@' . $contact['addr'];
843 $mention = '@' . $term['url'];
846 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
853 * Adds attachment data to the JSON document
855 * @param array $item Data of the item that is to be posted
856 * @param string $type Object type
858 * @return array with attachment data
859 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
861 private static function createAttachmentList($item, $type)
865 $arr = explode('[/attach],', $item['attach']);
867 foreach ($arr as $r) {
869 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
871 $attributes = ['type' => 'Document',
872 'mediaType' => $matches[3],
873 'url' => $matches[1],
876 if (trim($matches[4]) != '') {
877 $attributes['name'] = trim($matches[4]);
880 $attachments[] = $attributes;
885 if ($type != 'Note') {
889 // Simplify image codes
890 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
892 // Grab all pictures and create attachments out of them
893 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
894 foreach ($pictures[1] as $picture) {
895 $imgdata = Image::getInfoFromURL($picture);
897 $attachments[] = ['type' => 'Document',
898 'mediaType' => $imgdata['mime'],
909 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
911 * @param array $match Matching values for the callback
912 * @return string Replaced mention
913 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
915 private static function mentionCallback($match)
917 if (empty($match[1])) {
921 $data = Contact::getDetailsByURL($match[1]);
922 if (empty($data['nick'])) {
926 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
930 * Remove image elements and replaces them with links to the image
932 * @param string $body
934 * @return string with replaced elements
936 private static function removePictures($body)
938 // Simplify image codes
939 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
941 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
942 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
948 * Fetches the "context" value for a givem item array from the "conversation" table
952 * @return string with context url
955 private static function fetchContextURLForItem($item)
957 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
958 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
959 $context_uri = $conversation['conversation-href'];
960 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
961 $context_uri = $conversation['conversation-uri'];
963 $context_uri = $item['parent-uri'] . '#context';
969 * Returns if the post contains sensitive content ("nsfw")
971 * @param integer $item_id
976 private static function isSensitive($item_id)
978 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
979 return DBA::exists('term', $condition);
987 * @return array with the event data
988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
990 public static function createEvent($item)
993 $event['name'] = $item['event-summary'];
994 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
995 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
997 if (!$item['event-nofinish']) {
998 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1001 if (!empty($item['event-location'])) {
1002 $item['location'] = $item['event-location'];
1003 $event['location'] = self::createLocation($item);
1010 * Creates a note/article object array
1012 * @param array $item
1014 * @return array with the object data
1015 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1016 * @throws \ImagickException
1018 public static function createNote($item)
1020 if ($item['event-type'] == 'event') {
1022 } elseif (!empty($item['title'])) {
1028 if ($item['deleted']) {
1029 $type = 'Tombstone';
1033 $data['id'] = $item['uri'];
1034 $data['type'] = $type;
1036 if ($item['deleted']) {
1040 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1042 if ($item['uri'] != $item['thr-parent']) {
1043 $data['inReplyTo'] = $item['thr-parent'];
1045 $data['inReplyTo'] = null;
1048 $data['diaspora:guid'] = $item['guid'];
1049 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1051 if ($item['created'] != $item['edited']) {
1052 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1055 $data['url'] = $item['plink'];
1056 $data['attributedTo'] = $item['author-link'];
1057 $data['sensitive'] = self::isSensitive($item['id']);
1058 $data['context'] = self::fetchContextURLForItem($item);
1060 if (!empty($item['title'])) {
1061 $data['name'] = BBCode::toPlaintext($item['title'], false);
1064 $permission_block = self::createPermissionBlockForItem($item, false);
1066 $body = $item['body'];
1068 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1069 $body = self::prependMentions($body, $permission_block);
1072 if ($type == 'Note') {
1073 $body = self::removePictures($body);
1074 } elseif (($type == 'Article') && empty($data['summary'])) {
1075 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1078 if ($type == 'Event') {
1079 $data = array_merge($data, self::createEvent($item));
1081 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1082 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1084 $data['content'] = BBCode::convert($body, false, 7);
1087 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1089 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1090 $data['diaspora:comment'] = $item['signed_text'];
1093 $data['attachment'] = self::createAttachmentList($item, $type);
1094 $data['tag'] = self::createTagList($item);
1096 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1097 $data['location'] = self::createLocation($item);
1100 if (!empty($item['app'])) {
1101 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1104 $data = array_merge($data, $permission_block);
1110 * Creates an announce object entry
1112 * @param array $item
1113 * @param array $data activity data
1115 * @return array with activity data
1116 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1117 * @throws \ImagickException
1119 private static function createAnnounce($item, $data)
1121 $announce = api_share_as_retweet($item);
1122 if (empty($announce['plink'])) {
1123 $data['type'] = 'Create';
1124 $data['object'] = self::createNote($item);
1128 // Fetch the original id of the object
1129 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1130 if (!empty($activity)) {
1131 $ldactivity = JsonLD::compact($activity);
1132 $id = JsonLD::fetchElement($ldactivity, '@id');
1134 $data['object'] = $id;
1139 $data['type'] = 'Create';
1140 $data['object'] = self::createNote($item);
1145 * Creates an activity id for a given contact id
1147 * @param integer $cid Contact ID of target
1149 * @return bool|string activity id
1151 public static function activityIDFromContact($cid)
1153 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1154 if (!DBA::isResult($contact)) {
1158 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1159 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1160 return System::baseUrl() . '/activity/' . $uuid;
1164 * Transmits a contact suggestion to a given inbox
1166 * @param integer $uid User ID
1167 * @param string $inbox Target inbox
1168 * @param integer $suggestion_id Suggestion ID
1170 * @return boolean was the transmission successful?
1171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1173 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1175 $owner = User::getOwnerDataById($uid);
1177 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1179 $data = ['@context' => ActivityPub::CONTEXT,
1180 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1181 'type' => 'Announce',
1182 'actor' => $owner['url'],
1183 'object' => $suggestion['url'],
1184 'content' => $suggestion['note'],
1185 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1186 'to' => [ActivityPub::PUBLIC_COLLECTION],
1189 $signed = LDSignature::sign($data, $owner);
1191 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1192 return HTTPSignature::transmit($signed, $inbox, $uid);
1196 * Transmits a profile relocation to a given inbox
1198 * @param integer $uid User ID
1199 * @param string $inbox Target inbox
1201 * @return boolean was the transmission successful?
1202 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1204 public static function sendProfileRelocation($uid, $inbox)
1206 $owner = User::getOwnerDataById($uid);
1208 $data = ['@context' => ActivityPub::CONTEXT,
1209 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1210 'type' => 'dfrn:relocate',
1211 'actor' => $owner['url'],
1212 'object' => $owner['url'],
1213 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1214 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1215 'to' => [ActivityPub::PUBLIC_COLLECTION],
1218 $signed = LDSignature::sign($data, $owner);
1220 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1221 return HTTPSignature::transmit($signed, $inbox, $uid);
1225 * Transmits a profile deletion to a given inbox
1227 * @param integer $uid User ID
1228 * @param string $inbox Target inbox
1230 * @return boolean was the transmission successful?
1231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1233 public static function sendProfileDeletion($uid, $inbox)
1235 $owner = User::getOwnerDataById($uid);
1237 if (empty($owner)) {
1238 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1242 if (empty($owner['uprvkey'])) {
1243 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1247 $data = ['@context' => ActivityPub::CONTEXT,
1248 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1250 'actor' => $owner['url'],
1251 'object' => $owner['url'],
1252 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1253 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1254 'to' => [ActivityPub::PUBLIC_COLLECTION],
1257 $signed = LDSignature::sign($data, $owner);
1259 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1260 return HTTPSignature::transmit($signed, $inbox, $uid);
1264 * Transmits a profile change to a given inbox
1266 * @param integer $uid User ID
1267 * @param string $inbox Target inbox
1269 * @return boolean was the transmission successful?
1270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1271 * @throws \ImagickException
1273 public static function sendProfileUpdate($uid, $inbox)
1275 $owner = User::getOwnerDataById($uid);
1276 $profile = APContact::getByURL($owner['url']);
1278 $data = ['@context' => ActivityPub::CONTEXT,
1279 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1281 'actor' => $owner['url'],
1282 'object' => self::getProfile($uid),
1283 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1284 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1285 'to' => [$profile['followers']],
1288 $signed = LDSignature::sign($data, $owner);
1290 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1291 return HTTPSignature::transmit($signed, $inbox, $uid);
1295 * Transmits a given activity to a target
1297 * @param string $activity Type name
1298 * @param string $target Target profile
1299 * @param integer $uid User ID
1301 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1302 * @throws \ImagickException
1303 * @throws \Exception
1305 public static function sendActivity($activity, $target, $uid, $id = '')
1307 $profile = APContact::getByURL($target);
1309 $owner = User::getOwnerDataById($uid);
1312 $id = System::baseUrl() . '/activity/' . System::createGUID();
1315 $data = ['@context' => ActivityPub::CONTEXT,
1317 'type' => $activity,
1318 'actor' => $owner['url'],
1319 'object' => $profile['url'],
1320 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1321 'to' => [$profile['url']]];
1323 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1325 $signed = LDSignature::sign($data, $owner);
1326 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1330 * Transmits a "follow object" activity to a target
1331 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1333 * @param string $object Object URL
1334 * @param string $target Target profile
1335 * @param integer $uid User ID
1337 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1338 * @throws \ImagickException
1339 * @throws \Exception
1341 public static function sendFollowObject($object, $target, $uid = 0)
1343 $profile = APContact::getByURL($target);
1346 // Fetch the list of administrators
1347 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1349 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1350 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1351 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1352 $uid = $first_user['uid'];
1355 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1356 'author-id' => Contact::getPublicIdByUserId($uid)];
1357 if (Item::exists($condition)) {
1358 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1362 $owner = User::getOwnerDataById($uid);
1364 $data = ['@context' => ActivityPub::CONTEXT,
1365 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1367 'actor' => $owner['url'],
1368 'object' => $object,
1369 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1370 'to' => [$profile['url']]];
1372 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1374 $signed = LDSignature::sign($data, $owner);
1375 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1379 * Transmit a message that the contact request had been accepted
1381 * @param string $target Target profile
1383 * @param integer $uid User ID
1384 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1385 * @throws \ImagickException
1387 public static function sendContactAccept($target, $id, $uid)
1389 $profile = APContact::getByURL($target);
1391 $owner = User::getOwnerDataById($uid);
1392 $data = ['@context' => ActivityPub::CONTEXT,
1393 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1395 'actor' => $owner['url'],
1396 'object' => ['id' => $id, 'type' => 'Follow',
1397 'actor' => $profile['url'],
1398 'object' => $owner['url']],
1399 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1400 'to' => [$profile['url']]];
1402 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1404 $signed = LDSignature::sign($data, $owner);
1405 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1409 * Reject a contact request or terminates the contact relation
1411 * @param string $target Target profile
1413 * @param integer $uid User ID
1414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1415 * @throws \ImagickException
1417 public static function sendContactReject($target, $id, $uid)
1419 $profile = APContact::getByURL($target);
1421 $owner = User::getOwnerDataById($uid);
1422 $data = ['@context' => ActivityPub::CONTEXT,
1423 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1425 'actor' => $owner['url'],
1426 'object' => ['id' => $id, 'type' => 'Follow',
1427 'actor' => $profile['url'],
1428 'object' => $owner['url']],
1429 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1430 'to' => [$profile['url']]];
1432 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1434 $signed = LDSignature::sign($data, $owner);
1435 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1439 * Transmits a message that we don't want to follow this contact anymore
1441 * @param string $target Target profile
1442 * @param integer $uid User ID
1443 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1444 * @throws \ImagickException
1445 * @throws \Exception
1447 public static function sendContactUndo($target, $cid, $uid)
1449 $profile = APContact::getByURL($target);
1451 $object_id = self::activityIDFromContact($cid);
1452 if (empty($object_id)) {
1456 $id = System::baseUrl() . '/activity/' . System::createGUID();
1458 $owner = User::getOwnerDataById($uid);
1459 $data = ['@context' => ActivityPub::CONTEXT,
1462 'actor' => $owner['url'],
1463 'object' => ['id' => $object_id, 'type' => 'Follow',
1464 'actor' => $owner['url'],
1465 'object' => $profile['url']],
1466 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1467 'to' => [$profile['url']]];
1469 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1471 $signed = LDSignature::sign($data, $owner);
1472 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1475 private static function prependMentions($body, array $permission_block)
1477 if (Config::get('system', 'disable_implicit_mentions')) {
1483 foreach ($permission_block['to'] as $profile_url) {
1484 $profile = Contact::getDetailsByURL($profile_url);
1485 if (!empty($profile['addr'])
1486 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1487 && !strstr($body, $profile['addr'])
1488 && !strstr($body, $profile_url)
1490 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1494 $mentions[] = $body;
1496 return implode(' ', $mentions);