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 * Fetches a list of inboxes of followers of a given user
471 * @param integer $uid User ID
472 * @param boolean $personal fetch personal inboxes
474 * @return array of follower inboxes
475 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
476 * @throws \ImagickException
478 public static function fetchTargetInboxesforUser($uid, $personal = false)
482 if (Config::get('debug', 'total_ap_delivery')) {
483 // Will be activated in a later step
484 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
486 // For now only send to these contacts:
487 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
490 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
493 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
496 $contacts = DBA::select('contact', ['url'], $condition);
497 while ($contact = DBA::fetch($contacts)) {
498 if (Network::isUrlBlocked($contact['url'])) {
502 $profile = APContact::getByURL($contact['url'], false);
503 if (!empty($profile)) {
504 if (empty($profile['sharedinbox']) || $personal) {
505 $target = $profile['inbox'];
507 $target = $profile['sharedinbox'];
509 $inboxes[$target] = $target;
512 DBA::close($contacts);
518 * Fetches an array of inboxes for the given item and user
520 * @param array $item Item array
521 * @param integer $uid User ID
522 * @param boolean $personal fetch personal inboxes
523 * @param integer $last_id Last item id for adding receivers
524 * @param boolean $forum_mode "true" means that we are sending content to a forum
525 * @return array with inboxes
526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
527 * @throws \ImagickException
529 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
531 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
532 if (empty($permissions)) {
538 if ($item['gravity'] == GRAVITY_ACTIVITY) {
539 $item_profile = APContact::getByURL($item['author-link'], false);
541 $item_profile = APContact::getByURL($item['owner-link'], false);
544 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
545 if (empty($permissions[$element])) {
549 $blindcopy = in_array($element, ['bto', 'bcc']);
551 foreach ($permissions[$element] as $receiver) {
552 if (Network::isUrlBlocked($receiver)) {
556 if ($receiver == $item_profile['followers']) {
557 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
559 $profile = APContact::getByURL($receiver, false);
560 if (!empty($profile)) {
561 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
562 $target = $profile['inbox'];
564 $target = $profile['sharedinbox'];
566 $inboxes[$target] = $target;
576 * Returns the activity type of a given item
580 * @return string with activity type
581 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
582 * @throws \ImagickException
584 private static function getTypeOfItem($item)
588 // Only check for a reshare, if it is a real reshare and no quoted reshare
589 if (strpos($item['body'], "[share") === 0) {
590 $announce = api_share_as_retweet($item);
591 $reshared = !empty($announce['plink']);
596 } elseif ($item['verb'] == ACTIVITY_POST) {
597 if ($item['created'] == $item['edited']) {
602 } elseif ($item['verb'] == ACTIVITY_LIKE) {
604 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
606 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
608 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
610 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
611 $type = 'TentativeAccept';
612 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
622 * Creates the activity or fetches it from the cache
624 * @param integer $item_id
625 * @param boolean $force Force new cache entry
627 * @return array with the activity
630 public static function createCachedActivityFromItem($item_id, $force = false)
632 $cachekey = 'APDelivery:createActivity:' . $item_id;
635 $data = Cache::get($cachekey);
636 if (!is_null($data)) {
641 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
643 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
648 * Creates an activity array for a given item id
650 * @param integer $item_id
651 * @param boolean $object_mode Is the activity item is used inside another object?
653 * @return array of activity
656 public static function createActivityFromItem($item_id, $object_mode = false)
658 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
660 if (!DBA::isResult($item)) {
664 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
665 $owner = User::getOwnerDataById($item['uid']);
666 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
669 // Disguise forum posts as reshares. Will later be converted to a real announce
670 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
671 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
676 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
677 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
678 if (DBA::isResult($conversation)) {
679 $data = json_decode($conversation['source']);
685 $type = self::getTypeOfItem($item);
689 $data = ['@context' => ActivityPub::CONTEXT];
691 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
693 } elseif ($item['deleted']) {
700 $data['id'] = $item['uri'] . '#' . $type;
701 $data['type'] = $type;
703 if (Item::isForumPost($item) && ($type != 'Announce')) {
704 $data['actor'] = $item['author-link'];
706 $data['actor'] = $item['owner-link'];
709 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
711 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
713 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
715 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
716 $data['object'] = self::createNote($item);
717 } elseif ($data['type'] == 'Announce') {
718 $data = self::createAnnounce($item, $data);
719 } elseif ($data['type'] == 'Follow') {
720 $data['object'] = $item['parent-uri'];
721 } elseif ($data['type'] == 'Undo') {
722 $data['object'] = self::createActivityFromItem($item_id, true);
724 $data['diaspora:guid'] = $item['guid'];
725 if (!empty($item['signed_text'])) {
726 $data['diaspora:like'] = $item['signed_text'];
728 $data['object'] = $item['thr-parent'];
731 if (!empty($item['contact-uid'])) {
732 $uid = $item['contact-uid'];
737 $owner = User::getOwnerDataById($uid);
739 if (!$object_mode && !empty($owner)) {
740 return LDSignature::sign($data, $owner);
745 /// @todo Create "conversation" entry
749 * Creates an object array for a given item id
751 * @param integer $item_id
753 * @return array with the object data
754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
755 * @throws \ImagickException
757 public static function createObjectFromItemID($item_id)
759 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
761 if (!DBA::isResult($item)) {
765 $data = ['@context' => ActivityPub::CONTEXT];
766 $data = array_merge($data, self::createNote($item));
772 * Creates a location entry for a given item array
776 * @return array with location array
778 private static function createLocation($item)
780 $location = ['type' => 'Place'];
782 if (!empty($item['location'])) {
783 $location['name'] = $item['location'];
788 if (empty($item['coord'])) {
789 $coord = Map::getCoordinates($item['location']);
791 $coords = explode(' ', $item['coord']);
792 if (count($coords) == 2) {
793 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
797 if (!empty($coord['lat']) && !empty($coord['lon'])) {
798 $location['latitude'] = $coord['lat'];
799 $location['longitude'] = $coord['lon'];
806 * Returns a tag array for a given item array
810 * @return array of tags
811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
813 private static function createTagList($item)
817 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
818 foreach ($terms as $term) {
819 if ($term['type'] == Term::HASHTAG) {
820 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
821 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
822 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
823 $contact = Contact::getDetailsByURL($term['url']);
824 if (!empty($contact['addr'])) {
825 $mention = '@' . $contact['addr'];
827 $mention = '@' . $term['url'];
830 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
837 * Adds attachment data to the JSON document
839 * @param array $item Data of the item that is to be posted
840 * @param string $type Object type
842 * @return array with attachment data
843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
845 private static function createAttachmentList($item, $type)
849 $arr = explode('[/attach],', $item['attach']);
851 foreach ($arr as $r) {
853 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
855 $attributes = ['type' => 'Document',
856 'mediaType' => $matches[3],
857 'url' => $matches[1],
860 if (trim($matches[4]) != '') {
861 $attributes['name'] = trim($matches[4]);
864 $attachments[] = $attributes;
869 if ($type != 'Note') {
873 // Simplify image codes
874 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
876 // Grab all pictures and create attachments out of them
877 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
878 foreach ($pictures[1] as $picture) {
879 $imgdata = Image::getInfoFromURL($picture);
881 $attachments[] = ['type' => 'Document',
882 'mediaType' => $imgdata['mime'],
893 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
895 * @param array $match Matching values for the callback
896 * @return string Replaced mention
897 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
899 private static function mentionCallback($match)
901 if (empty($match[1])) {
905 $data = Contact::getDetailsByURL($match[1]);
906 if (empty($data['nick'])) {
910 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
914 * Remove image elements and replaces them with links to the image
916 * @param string $body
918 * @return string with replaced elements
920 private static function removePictures($body)
922 // Simplify image codes
923 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
925 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
926 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
932 * Fetches the "context" value for a givem item array from the "conversation" table
936 * @return string with context url
939 private static function fetchContextURLForItem($item)
941 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
942 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
943 $context_uri = $conversation['conversation-href'];
944 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
945 $context_uri = $conversation['conversation-uri'];
947 $context_uri = $item['parent-uri'] . '#context';
953 * Returns if the post contains sensitive content ("nsfw")
955 * @param integer $item_id
960 private static function isSensitive($item_id)
962 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
963 return DBA::exists('term', $condition);
971 * @return array with the event data
972 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
974 public static function createEvent($item)
977 $event['name'] = $item['event-summary'];
978 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
979 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
981 if (!$item['event-nofinish']) {
982 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
985 if (!empty($item['event-location'])) {
986 $item['location'] = $item['event-location'];
987 $event['location'] = self::createLocation($item);
994 * Creates a note/article object array
998 * @return array with the object data
999 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1000 * @throws \ImagickException
1002 public static function createNote($item)
1004 if ($item['event-type'] == 'event') {
1006 } elseif (!empty($item['title'])) {
1012 if ($item['deleted']) {
1013 $type = 'Tombstone';
1017 $data['id'] = $item['uri'];
1018 $data['type'] = $type;
1020 if ($item['deleted']) {
1024 $data['summary'] = BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB);
1026 if ($item['uri'] != $item['thr-parent']) {
1027 $data['inReplyTo'] = $item['thr-parent'];
1029 $data['inReplyTo'] = null;
1032 $data['diaspora:guid'] = $item['guid'];
1033 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1035 if ($item['created'] != $item['edited']) {
1036 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1039 $data['url'] = $item['plink'];
1040 $data['attributedTo'] = $item['author-link'];
1041 $data['sensitive'] = self::isSensitive($item['id']);
1042 $data['context'] = self::fetchContextURLForItem($item);
1044 if (!empty($item['title'])) {
1045 $data['name'] = BBCode::toPlaintext($item['title'], false);
1048 $permission_block = self::createPermissionBlockForItem($item, false);
1050 $body = $item['body'];
1052 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1053 $body = self::prependMentions($body, $permission_block);
1056 if ($type == 'Note') {
1057 $body = self::removePictures($body);
1058 } elseif (($type == 'Article') && empty($data['summary'])) {
1059 $data['summary'] = Plaintext::shorten(self::removePictures($body), 1000);
1062 if ($type == 'Event') {
1063 $data = array_merge($data, self::createEvent($item));
1065 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1066 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1068 $data['content'] = BBCode::convert($body, false, 7);
1071 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1073 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1074 $data['diaspora:comment'] = $item['signed_text'];
1077 $data['attachment'] = self::createAttachmentList($item, $type);
1078 $data['tag'] = self::createTagList($item);
1080 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1081 $data['location'] = self::createLocation($item);
1084 if (!empty($item['app'])) {
1085 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1088 $data = array_merge($data, $permission_block);
1094 * Creates an announce object entry
1096 * @param array $item
1097 * @param array $data activity data
1099 * @return array with activity data
1100 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1101 * @throws \ImagickException
1103 private static function createAnnounce($item, $data)
1105 $announce = api_share_as_retweet($item);
1106 if (empty($announce['plink'])) {
1107 $data['type'] = 'Create';
1108 $data['object'] = self::createNote($item);
1112 // Fetch the original id of the object
1113 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1114 if (!empty($activity)) {
1115 $ldactivity = JsonLD::compact($activity);
1116 $id = JsonLD::fetchElement($ldactivity, '@id');
1118 $data['object'] = $id;
1123 $data['type'] = 'Create';
1124 $data['object'] = self::createNote($item);
1129 * Creates an activity id for a given contact id
1131 * @param integer $cid Contact ID of target
1133 * @return bool|string activity id
1135 public static function activityIDFromContact($cid)
1137 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1138 if (!DBA::isResult($contact)) {
1142 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1143 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1144 return System::baseUrl() . '/activity/' . $uuid;
1148 * Transmits a contact suggestion to a given inbox
1150 * @param integer $uid User ID
1151 * @param string $inbox Target inbox
1152 * @param integer $suggestion_id Suggestion ID
1154 * @return boolean was the transmission successful?
1155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1157 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1159 $owner = User::getOwnerDataById($uid);
1161 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1163 $data = ['@context' => ActivityPub::CONTEXT,
1164 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1165 'type' => 'Announce',
1166 'actor' => $owner['url'],
1167 'object' => $suggestion['url'],
1168 'content' => $suggestion['note'],
1169 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1170 'to' => [ActivityPub::PUBLIC_COLLECTION],
1173 $signed = LDSignature::sign($data, $owner);
1175 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1176 return HTTPSignature::transmit($signed, $inbox, $uid);
1180 * Transmits a profile relocation to a given inbox
1182 * @param integer $uid User ID
1183 * @param string $inbox Target inbox
1185 * @return boolean was the transmission successful?
1186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1188 public static function sendProfileRelocation($uid, $inbox)
1190 $owner = User::getOwnerDataById($uid);
1192 $data = ['@context' => ActivityPub::CONTEXT,
1193 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1194 'type' => 'dfrn:relocate',
1195 'actor' => $owner['url'],
1196 'object' => $owner['url'],
1197 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1198 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1199 'to' => [ActivityPub::PUBLIC_COLLECTION],
1202 $signed = LDSignature::sign($data, $owner);
1204 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1205 return HTTPSignature::transmit($signed, $inbox, $uid);
1209 * Transmits a profile deletion to a given inbox
1211 * @param integer $uid User ID
1212 * @param string $inbox Target inbox
1214 * @return boolean was the transmission successful?
1215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1217 public static function sendProfileDeletion($uid, $inbox)
1219 $owner = User::getOwnerDataById($uid);
1221 if (empty($owner)) {
1222 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1226 if (empty($owner['uprvkey'])) {
1227 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1231 $data = ['@context' => ActivityPub::CONTEXT,
1232 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1234 'actor' => $owner['url'],
1235 'object' => $owner['url'],
1236 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1237 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1238 'to' => [ActivityPub::PUBLIC_COLLECTION],
1241 $signed = LDSignature::sign($data, $owner);
1243 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1244 return HTTPSignature::transmit($signed, $inbox, $uid);
1248 * Transmits a profile change to a given inbox
1250 * @param integer $uid User ID
1251 * @param string $inbox Target inbox
1253 * @return boolean was the transmission successful?
1254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1255 * @throws \ImagickException
1257 public static function sendProfileUpdate($uid, $inbox)
1259 $owner = User::getOwnerDataById($uid);
1260 $profile = APContact::getByURL($owner['url']);
1262 $data = ['@context' => ActivityPub::CONTEXT,
1263 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1265 'actor' => $owner['url'],
1266 'object' => self::getProfile($uid),
1267 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1268 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1269 'to' => [$profile['followers']],
1272 $signed = LDSignature::sign($data, $owner);
1274 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1275 return HTTPSignature::transmit($signed, $inbox, $uid);
1279 * Transmits a given activity to a target
1281 * @param string $activity Type name
1282 * @param string $target Target profile
1283 * @param integer $uid User ID
1285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1286 * @throws \ImagickException
1287 * @throws \Exception
1289 public static function sendActivity($activity, $target, $uid, $id = '')
1291 $profile = APContact::getByURL($target);
1293 $owner = User::getOwnerDataById($uid);
1296 $id = System::baseUrl() . '/activity/' . System::createGUID();
1299 $data = ['@context' => ActivityPub::CONTEXT,
1301 'type' => $activity,
1302 'actor' => $owner['url'],
1303 'object' => $profile['url'],
1304 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1305 'to' => [$profile['url']]];
1307 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1309 $signed = LDSignature::sign($data, $owner);
1310 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1314 * Transmits a "follow object" activity to a target
1315 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1317 * @param string $object Object URL
1318 * @param string $target Target profile
1319 * @param integer $uid User ID
1321 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1322 * @throws \ImagickException
1323 * @throws \Exception
1325 public static function sendFollowObject($object, $target, $uid = 0)
1327 $profile = APContact::getByURL($target);
1330 // Fetch the list of administrators
1331 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1333 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1334 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1335 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1336 $uid = $first_user['uid'];
1339 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1340 'author-id' => Contact::getPublicIdByUserId($uid)];
1341 if (Item::exists($condition)) {
1342 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1346 $owner = User::getOwnerDataById($uid);
1348 $data = ['@context' => ActivityPub::CONTEXT,
1349 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1351 'actor' => $owner['url'],
1352 'object' => $object,
1353 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1354 'to' => [$profile['url']]];
1356 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1358 $signed = LDSignature::sign($data, $owner);
1359 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1363 * Transmit a message that the contact request had been accepted
1365 * @param string $target Target profile
1367 * @param integer $uid User ID
1368 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1369 * @throws \ImagickException
1371 public static function sendContactAccept($target, $id, $uid)
1373 $profile = APContact::getByURL($target);
1375 $owner = User::getOwnerDataById($uid);
1376 $data = ['@context' => ActivityPub::CONTEXT,
1377 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1379 'actor' => $owner['url'],
1380 'object' => ['id' => $id, 'type' => 'Follow',
1381 'actor' => $profile['url'],
1382 'object' => $owner['url']],
1383 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1384 'to' => [$profile['url']]];
1386 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1388 $signed = LDSignature::sign($data, $owner);
1389 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1393 * Reject a contact request or terminates the contact relation
1395 * @param string $target Target profile
1397 * @param integer $uid User ID
1398 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1399 * @throws \ImagickException
1401 public static function sendContactReject($target, $id, $uid)
1403 $profile = APContact::getByURL($target);
1405 $owner = User::getOwnerDataById($uid);
1406 $data = ['@context' => ActivityPub::CONTEXT,
1407 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1409 'actor' => $owner['url'],
1410 'object' => ['id' => $id, 'type' => 'Follow',
1411 'actor' => $profile['url'],
1412 'object' => $owner['url']],
1413 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1414 'to' => [$profile['url']]];
1416 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1418 $signed = LDSignature::sign($data, $owner);
1419 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1423 * Transmits a message that we don't want to follow this contact anymore
1425 * @param string $target Target profile
1426 * @param integer $uid User ID
1427 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1428 * @throws \ImagickException
1429 * @throws \Exception
1431 public static function sendContactUndo($target, $cid, $uid)
1433 $profile = APContact::getByURL($target);
1435 $object_id = self::activityIDFromContact($cid);
1436 if (empty($object_id)) {
1440 $id = System::baseUrl() . '/activity/' . System::createGUID();
1442 $owner = User::getOwnerDataById($uid);
1443 $data = ['@context' => ActivityPub::CONTEXT,
1446 'actor' => $owner['url'],
1447 'object' => ['id' => $object_id, 'type' => 'Follow',
1448 'actor' => $owner['url'],
1449 'object' => $profile['url']],
1450 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1451 'to' => [$profile['url']]];
1453 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1455 $signed = LDSignature::sign($data, $owner);
1456 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1459 private static function prependMentions($body, array $permission_block)
1461 if (Config::get('system', 'disable_implicit_mentions')) {
1467 foreach ($permission_block['to'] as $profile_url) {
1468 $profile = Contact::getDetailsByURL($profile_url);
1469 if (!empty($profile['addr'])
1470 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1471 && !strstr($body, $profile['addr'])
1472 && !strstr($body, $profile_url)
1474 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1478 $mentions[] = $body;
1480 return implode(' ', $mentions);