3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Core\Logger;
10 use Friendica\Core\System;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\APContact;
16 use Friendica\Model\Item;
17 use Friendica\Model\Term;
18 use Friendica\Model\User;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Util\JsonLD;
22 use Friendica\Util\LDSignature;
23 use Friendica\Model\Profile;
24 use Friendica\Core\Config;
25 use Friendica\Object\Image;
26 use Friendica\Protocol\ActivityPub;
27 use Friendica\Protocol\Diaspora;
28 use Friendica\Core\Cache;
29 use Friendica\Util\Map;
30 use Friendica\Util\Network;
32 require_once 'include/api.php';
35 * @brief ActivityPub Transmitter Protocol class
43 * collects the lost of followers of the given owner
45 * @param array $owner Owner array
46 * @param integer $page Page number
48 * @return array of owners
50 public static function getFollowers($owner, $page = null)
52 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
53 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
54 $count = DBA::count('contact', $condition);
56 $data = ['@context' => ActivityPub::CONTEXT];
57 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
58 $data['type'] = 'OrderedCollection';
59 $data['totalItems'] = $count;
61 // When we hide our friends we will only show the pure number but don't allow more.
62 $profile = Profile::getByUID($owner['uid']);
63 if (!empty($profile['hide-friends'])) {
68 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
72 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
73 while ($contact = DBA::fetch($contacts)) {
74 $list[] = $contact['url'];
78 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
81 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
83 $data['orderedItems'] = $list;
90 * Create list of following contacts
92 * @param array $owner Owner array
93 * @param integer $page Page numbe
95 * @return array of following contacts
97 public static function getFollowing($owner, $page = null)
99 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
100 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
101 $count = DBA::count('contact', $condition);
103 $data = ['@context' => ActivityPub::CONTEXT];
104 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
105 $data['type'] = 'OrderedCollection';
106 $data['totalItems'] = $count;
108 // When we hide our friends we will only show the pure number but don't allow more.
109 $profile = Profile::getByUID($owner['uid']);
110 if (!empty($profile['hide-friends'])) {
115 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
119 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
120 while ($contact = DBA::fetch($contacts)) {
121 $list[] = $contact['url'];
125 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
128 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
130 $data['orderedItems'] = $list;
137 * Public posts for the given owner
139 * @param array $owner Owner array
140 * @param integer $page Page numbe
142 * @return array of posts
144 public static function getOutbox($owner, $page = null)
146 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
148 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
149 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
150 'deleted' => false, 'visible' => true];
151 $count = DBA::count('item', $condition);
153 $data = ['@context' => ActivityPub::CONTEXT];
154 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
155 $data['type'] = 'OrderedCollection';
156 $data['totalItems'] = $count;
159 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
163 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
165 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
166 while ($item = Item::fetch($items)) {
167 $object = self::createObjectFromItemID($item['id']);
168 unset($object['@context']);
173 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
176 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
178 $data['orderedItems'] = $list;
185 * Return the ActivityPub profile of the given user
187 * @param integer $uid User ID
188 * @return array with profile data
190 public static function getProfile($uid)
192 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
193 'account_removed' => false, 'verified' => true];
194 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
195 $user = DBA::selectFirst('user', $fields, $condition);
196 if (!DBA::isResult($user)) {
200 $fields = ['locality', 'region', 'country-name'];
201 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
202 if (!DBA::isResult($profile)) {
206 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
207 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
208 if (!DBA::isResult($contact)) {
212 // On old installations and never changed contacts this might not be filled
213 if (empty($contact['avatar'])) {
214 $contact['avatar'] = $contact['photo'];
217 $data = ['@context' => ActivityPub::CONTEXT];
218 $data['id'] = $contact['url'];
219 $data['diaspora:guid'] = $user['guid'];
220 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
221 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
222 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
223 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
224 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
225 $data['preferredUsername'] = $user['nickname'];
226 $data['name'] = $contact['name'];
227 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
228 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
229 $data['summary'] = $contact['about'];
230 $data['url'] = $contact['url'];
231 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
232 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
233 'owner' => $contact['url'],
234 'publicKeyPem' => $user['pubkey']];
235 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
236 $data['icon'] = ['type' => 'Image',
237 'url' => $contact['avatar']];
239 // tags: https://kitty.town/@inmysocks/100656097926961126.json
244 * Returns an array with permissions of a given item array
248 * @return array with permissions
250 private static function fetchPermissionBlockFromConversation($item)
252 if (empty($item['thr-parent'])) {
256 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
257 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
258 if (!DBA::isResult($conversation)) {
262 $activity = json_decode($conversation['source'], true);
264 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
265 $profile = APContact::getByURL($actor);
267 $item_profile = APContact::getByURL($item['author-link']);
268 $exclude[] = $item['author-link'];
270 if ($item['gravity'] == GRAVITY_PARENT) {
271 $exclude[] = $item['owner-link'];
274 $permissions['to'][] = $actor;
276 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
277 if (empty($activity[$element])) {
280 if (is_string($activity[$element])) {
281 $activity[$element] = [$activity[$element]];
284 foreach ($activity[$element] as $receiver) {
285 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
286 $permissions[$element][] = $item_profile['followers'];
287 } elseif (!in_array($receiver, $exclude)) {
288 $permissions[$element][] = $receiver;
296 * Creates an array of permissions from an item thread
299 * @param boolean $blindcopy
300 * @param boolean $last_id
302 * @return array with permission data
304 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
307 $last_id = $item['id'];
312 // Check if we should always deliver our stuff via BCC
313 if (!empty($item['uid'])) {
314 $profile = Profile::getByUID($item['uid']);
315 if (!empty($profile)) {
316 $always_bcc = $profile['hide-friends'];
320 // Will be activated in a later step
321 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
323 // For now only send to these contacts:
324 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
326 $data = ['to' => [], 'cc' => [], 'bcc' => []];
328 $actor_profile = APContact::getByURL($item['author-link']);
330 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
332 if (!$item['private']) {
333 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
335 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
336 if (!empty($actor_profile['followers'])) {
337 $data['cc'][] = $actor_profile['followers'];
340 foreach ($terms as $term) {
341 $profile = APContact::getByURL($term['url'], false);
342 if (!empty($profile)) {
343 $data['to'][] = $profile['url'];
347 $receiver_list = Item::enumeratePermissions($item);
351 foreach ($terms as $term) {
352 $cid = Contact::getIdForURL($term['url'], $item['uid']);
353 if (!empty($cid) && in_array($cid, $receiver_list)) {
354 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
355 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
356 $data['to'][] = $profile['url'];
361 foreach ($receiver_list as $receiver) {
362 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
363 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
364 if ($contact['hidden'] || $always_bcc) {
365 $data['bcc'][] = $profile['url'];
367 $data['cc'][] = $profile['url'];
373 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
374 while ($parent = Item::fetch($parents)) {
375 // Don't include data from future posts
376 if ($parent['id'] >= $last_id) {
380 $profile = APContact::getByURL($parent['author-link'], false);
381 if (!empty($profile)) {
382 if ($parent['uri'] == $item['thr-parent']) {
383 $data['to'][] = $profile['url'];
385 $data['cc'][] = $profile['url'];
389 if ($item['gravity'] != GRAVITY_PARENT) {
393 $profile = APContact::getByURL($parent['owner-link'], false);
394 if (!empty($profile)) {
395 $data['cc'][] = $profile['url'];
398 DBA::close($parents);
400 $data['to'] = array_unique($data['to']);
401 $data['cc'] = array_unique($data['cc']);
402 $data['bcc'] = array_unique($data['bcc']);
404 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
405 unset($data['to'][$key]);
408 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
409 unset($data['cc'][$key]);
412 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
413 unset($data['bcc'][$key]);
416 foreach ($data['to'] as $to) {
417 if (($key = array_search($to, $data['cc'])) !== false) {
418 unset($data['cc'][$key]);
421 if (($key = array_search($to, $data['bcc'])) !== false) {
422 unset($data['bcc'][$key]);
426 foreach ($data['cc'] as $cc) {
427 if (($key = array_search($cc, $data['bcc'])) !== false) {
428 unset($data['bcc'][$key]);
432 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
435 unset($receivers['bcc']);
442 * Fetches a list of inboxes of followers of a given user
444 * @param integer $uid User ID
445 * @param boolean $personal fetch personal inboxes
447 * @return array of follower inboxes
449 public static function fetchTargetInboxesforUser($uid, $personal = false)
453 // Will be activated in a later step
454 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
456 // For now only send to these contacts:
457 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
459 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
462 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
465 $contacts = DBA::select('contact', ['url'], $condition);
466 while ($contact = DBA::fetch($contacts)) {
467 if (Network::isUrlBlocked($contact['url'])) {
471 $profile = APContact::getByURL($contact['url'], false);
472 if (!empty($profile)) {
473 if (empty($profile['sharedinbox']) || $personal) {
474 $target = $profile['inbox'];
476 $target = $profile['sharedinbox'];
478 $inboxes[$target] = $target;
481 DBA::close($contacts);
487 * Fetches an array of inboxes for the given item and user
490 * @param integer $uid User ID
491 * @param boolean $personal fetch personal inboxes
492 * @param integer $last_id Last item id for adding receivers
494 * @return array with inboxes
496 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
498 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
499 if (empty($permissions)) {
505 if ($item['gravity'] == GRAVITY_ACTIVITY) {
506 $item_profile = APContact::getByURL($item['author-link'], false);
508 $item_profile = APContact::getByURL($item['owner-link'], false);
511 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
512 if (empty($permissions[$element])) {
516 $blindcopy = in_array($element, ['bto', 'bcc']);
518 foreach ($permissions[$element] as $receiver) {
519 if (Network::isUrlBlocked($receiver)) {
523 if ($receiver == $item_profile['followers']) {
524 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
526 $profile = APContact::getByURL($receiver, false);
527 if (!empty($profile)) {
528 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
529 $target = $profile['inbox'];
531 $target = $profile['sharedinbox'];
533 $inboxes[$target] = $target;
543 * Returns the activity type of a given item
547 * @return string with activity type
549 private static function getTypeOfItem($item)
553 // Only check for a reshare, if it is a real reshare and no quoted reshare
554 if (strpos($item['body'], "[share") === 0) {
555 $announce = api_share_as_retweet($item);
556 $reshared = !empty($announce['plink']);
561 } elseif ($item['verb'] == ACTIVITY_POST) {
562 if ($item['created'] == $item['edited']) {
567 } elseif ($item['verb'] == ACTIVITY_LIKE) {
569 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
571 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
573 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
575 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
576 $type = 'TentativeAccept';
585 * Creates the activity or fetches it from the cache
587 * @param integer $item_id
588 * @param boolean $force Force new cache entry
590 * @return array with the activity
592 public static function createCachedActivityFromItem($item_id, $force = false)
594 $cachekey = 'APDelivery:createActivity:' . $item_id;
597 $data = Cache::get($cachekey);
598 if (!is_null($data)) {
603 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
605 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
610 * Creates an activity array for a given item id
612 * @param integer $item_id
613 * @param boolean $object_mode Is the activity item is used inside another object?
615 * @return array of activity
617 public static function createActivityFromItem($item_id, $object_mode = false)
619 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
621 if (!DBA::isResult($item)) {
625 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
626 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
627 if (DBA::isResult($conversation)) {
628 $data = json_decode($conversation['source']);
634 $type = self::getTypeOfItem($item);
637 $data = ['@context' => ActivityPub::CONTEXT];
639 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
641 } elseif ($item['deleted']) {
648 $data['id'] = $item['uri'] . '#' . $type;
649 $data['type'] = $type;
650 $data['actor'] = $item['owner-link'];
652 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
654 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
656 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
658 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
659 $data['object'] = self::createNote($item);
660 } elseif ($data['type'] == 'Announce') {
661 $data['object'] = self::createAnnounce($item);
662 } elseif ($data['type'] == 'Undo') {
663 $data['object'] = self::createActivityFromItem($item_id, true);
665 $data['diaspora:guid'] = $item['guid'];
666 if (!empty($item['signed_text'])) {
667 $data['diaspora:like'] = $item['signed_text'];
669 $data['object'] = $item['thr-parent'];
672 if (!empty($item['contact-uid'])) {
673 $uid = $item['contact-uid'];
678 $owner = User::getOwnerDataById($uid);
680 if (!$object_mode && !empty($owner)) {
681 return LDSignature::sign($data, $owner);
686 /// @todo Create "conversation" entry
690 * Creates an object array for a given item id
692 * @param integer $item_id
694 * @return array with the object data
696 public static function createObjectFromItemID($item_id)
698 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
700 if (!DBA::isResult($item)) {
704 $data = ['@context' => ActivityPub::CONTEXT];
705 $data = array_merge($data, self::createNote($item));
711 * Creates a location entry for a given item array
715 * @return array with location array
717 private static function createLocation($item)
719 $location = ['type' => 'Place'];
721 if (!empty($item['location'])) {
722 $location['name'] = $item['location'];
727 if (empty($item['coord'])) {
728 $coord = Map::getCoordinates($item['location']);
730 $coords = explode(' ', $item['coord']);
731 if (count($coords) == 2) {
732 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
736 if (!empty($coord['lat']) && !empty($coord['lon'])) {
737 $location['latitude'] = $coord['lat'];
738 $location['longitude'] = $coord['lon'];
745 * Returns a tag array for a given item array
749 * @return array of tags
751 private static function createTagList($item)
755 $terms = Term::tagArrayFromItemId($item['id']);
756 foreach ($terms as $term) {
757 if ($term['type'] == TERM_HASHTAG) {
758 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
759 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
760 } elseif ($term['type'] == TERM_MENTION) {
761 $contact = Contact::getDetailsByURL($term['url']);
762 if (!empty($contact['addr'])) {
763 $mention = '@' . $contact['addr'];
765 $mention = '@' . $term['url'];
768 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
775 * Adds attachment data to the JSON document
777 * @param array $item Data of the item that is to be posted
778 * @param text $type Object type
780 * @return array with attachment data
782 private static function createAttachmentList($item, $type)
786 $arr = explode('[/attach],', $item['attach']);
788 foreach ($arr as $r) {
790 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
792 $attributes = ['type' => 'Document',
793 'mediaType' => $matches[3],
794 'url' => $matches[1],
797 if (trim($matches[4]) != '') {
798 $attributes['name'] = trim($matches[4]);
801 $attachments[] = $attributes;
806 if ($type != 'Note') {
810 // Simplify image codes
811 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
813 // Grab all pictures and create attachments out of them
814 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
815 foreach ($pictures[1] as $picture) {
816 $imgdata = Image::getInfoFromURL($picture);
818 $attachments[] = ['type' => 'Document',
819 'mediaType' => $imgdata['mime'],
830 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
832 * @param array $match Matching values for the callback
833 * @return string Replaced mention
835 private static function mentionCallback($match)
837 if (empty($match[1])) {
841 $data = Contact::getDetailsByURL($match[1]);
842 if (empty($data) || empty($data['nick'])) {
846 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
850 * Remove image elements and replaces them with links to the image
852 * @param string $body
854 * @return string with replaced elements
856 private static function removePictures($body)
858 // Simplify image codes
859 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
861 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
862 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
868 * Fetches the "context" value for a givem item array from the "conversation" table
872 * @return string with context url
874 private static function fetchContextURLForItem($item)
876 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
877 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
878 $context_uri = $conversation['conversation-href'];
879 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
880 $context_uri = $conversation['conversation-uri'];
882 $context_uri = $item['parent-uri'] . '#context';
888 * Returns if the post contains sensitive content ("nsfw")
890 * @param integer $item_id
894 private static function isSensitive($item_id)
896 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
897 return DBA::exists('term', $condition);
905 * @return array with the event data
907 public static function createEvent($item)
910 $event['name'] = $item['event-summary'];
911 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
912 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
914 if (!$item['event-nofinish']) {
915 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
918 if (!empty($item['event-location'])) {
919 $item['location'] = $item['event-location'];
920 $event['location'] = self::createLocation($item);
927 * Creates a note/article object array
931 * @return array with the object data
933 public static function createNote($item)
935 if ($item['event-type'] == 'event') {
937 } elseif (!empty($item['title'])) {
943 if ($item['deleted']) {
948 $data['id'] = $item['uri'];
949 $data['type'] = $type;
951 if ($item['deleted']) {
955 $data['summary'] = null; // Ignore by now
957 if ($item['uri'] != $item['thr-parent']) {
958 $data['inReplyTo'] = $item['thr-parent'];
960 $data['inReplyTo'] = null;
963 $data['diaspora:guid'] = $item['guid'];
964 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
966 if ($item['created'] != $item['edited']) {
967 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
970 $data['url'] = $item['plink'];
971 $data['attributedTo'] = $item['author-link'];
972 $data['sensitive'] = self::isSensitive($item['id']);
973 $data['context'] = self::fetchContextURLForItem($item);
975 if (!empty($item['title'])) {
976 $data['name'] = BBCode::toPlaintext($item['title'], false);
979 $body = $item['body'];
981 if ($type == 'Note') {
982 $body = self::removePictures($body);
985 if ($type == 'Event') {
986 $data = array_merge($data, self::createEvent($item));
988 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
989 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
991 $data['content'] = BBCode::convert($body, false, 7);
994 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
996 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
997 $data['diaspora:comment'] = $item['signed_text'];
1000 $data['attachment'] = self::createAttachmentList($item, $type);
1001 $data['tag'] = self::createTagList($item);
1003 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1004 $data['location'] = self::createLocation($item);
1007 if (!empty($item['app'])) {
1008 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1011 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1017 * Creates an announce object entry
1019 * @param array $item
1021 * @return string with announced object url
1023 public static function createAnnounce($item)
1025 $announce = api_share_as_retweet($item);
1026 if (empty($announce['plink'])) {
1027 return self::createNote($item);
1030 // Fetch the original id of the object
1031 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1032 if (!empty($activity)) {
1033 $ldactivity = JsonLD::compact($activity);
1034 $id = JsonLD::fetchElement($ldactivity, '@id');
1040 return self::createNote($item);
1044 * Creates an activity id for a given contact id
1046 * @param integer $cid Contact ID of target
1048 * @return bool|string activity id
1050 public static function activityIDFromContact($cid)
1052 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1053 if (!DBA::isResult($contact)) {
1057 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1058 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1059 return System::baseUrl() . '/activity/' . $uuid;
1063 * Transmits a contact suggestion to a given inbox
1065 * @param integer $uid User ID
1066 * @param string $inbox Target inbox
1067 * @param integer $suggestion_id Suggestion ID
1069 * @return boolean was the transmission successful?
1071 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1073 $owner = User::getOwnerDataById($uid);
1075 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1077 $data = ['@context' => ActivityPub::CONTEXT,
1078 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1079 'type' => 'Announce',
1080 'actor' => $owner['url'],
1081 'object' => $suggestion['url'],
1082 'content' => $suggestion['note'],
1083 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1084 'to' => [ActivityPub::PUBLIC_COLLECTION],
1087 $signed = LDSignature::sign($data, $owner);
1089 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1090 return HTTPSignature::transmit($signed, $inbox, $uid);
1094 * Transmits a profile relocation to a given inbox
1096 * @param integer $uid User ID
1097 * @param string $inbox Target inbox
1099 * @return boolean was the transmission successful?
1101 public static function sendProfileRelocation($uid, $inbox)
1103 $owner = User::getOwnerDataById($uid);
1105 $data = ['@context' => ActivityPub::CONTEXT,
1106 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1107 'type' => 'dfrn:relocate',
1108 'actor' => $owner['url'],
1109 'object' => $owner['url'],
1110 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1111 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1112 'to' => [ActivityPub::PUBLIC_COLLECTION],
1115 $signed = LDSignature::sign($data, $owner);
1117 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1118 return HTTPSignature::transmit($signed, $inbox, $uid);
1122 * Transmits a profile deletion to a given inbox
1124 * @param integer $uid User ID
1125 * @param string $inbox Target inbox
1127 * @return boolean was the transmission successful?
1129 public static function sendProfileDeletion($uid, $inbox)
1131 $owner = User::getOwnerDataById($uid);
1133 $data = ['@context' => ActivityPub::CONTEXT,
1134 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1136 'actor' => $owner['url'],
1137 'object' => $owner['url'],
1138 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1139 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1140 'to' => [ActivityPub::PUBLIC_COLLECTION],
1143 $signed = LDSignature::sign($data, $owner);
1145 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1146 return HTTPSignature::transmit($signed, $inbox, $uid);
1150 * Transmits a profile change to a given inbox
1152 * @param integer $uid User ID
1153 * @param string $inbox Target inbox
1155 * @return boolean was the transmission successful?
1157 public static function sendProfileUpdate($uid, $inbox)
1159 $owner = User::getOwnerDataById($uid);
1160 $profile = APContact::getByURL($owner['url']);
1162 $data = ['@context' => ActivityPub::CONTEXT,
1163 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1165 'actor' => $owner['url'],
1166 'object' => self::getProfile($uid),
1167 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1168 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1169 'to' => [$profile['followers']],
1172 $signed = LDSignature::sign($data, $owner);
1174 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1175 return HTTPSignature::transmit($signed, $inbox, $uid);
1179 * Transmits a given activity to a target
1181 * @param array $activity
1182 * @param string $target Target profile
1183 * @param integer $uid User ID
1184 * @param string $id activity id
1186 public static function sendActivity($activity, $target, $uid, $id = '')
1188 $profile = APContact::getByURL($target);
1190 $owner = User::getOwnerDataById($uid);
1193 $id = System::baseUrl() . '/activity/' . System::createGUID();
1196 $data = ['@context' => ActivityPub::CONTEXT,
1198 'type' => $activity,
1199 'actor' => $owner['url'],
1200 'object' => $profile['url'],
1201 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1202 'to' => [$profile['url']]];
1204 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1206 $signed = LDSignature::sign($data, $owner);
1207 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1211 * Transmit a message that the contact request had been accepted
1213 * @param string $target Target profile
1215 * @param integer $uid User ID
1217 public static function sendContactAccept($target, $id, $uid)
1219 $profile = APContact::getByURL($target);
1221 $owner = User::getOwnerDataById($uid);
1222 $data = ['@context' => ActivityPub::CONTEXT,
1223 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1225 'actor' => $owner['url'],
1226 'object' => ['id' => $id, 'type' => 'Follow',
1227 'actor' => $profile['url'],
1228 'object' => $owner['url']],
1229 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1230 'to' => [$profile['url']]];
1232 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1234 $signed = LDSignature::sign($data, $owner);
1235 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1239 * Reject a contact request or terminates the contact relation
1241 * @param string $target Target profile
1243 * @param integer $uid User ID
1245 public static function sendContactReject($target, $id, $uid)
1247 $profile = APContact::getByURL($target);
1249 $owner = User::getOwnerDataById($uid);
1250 $data = ['@context' => ActivityPub::CONTEXT,
1251 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1253 'actor' => $owner['url'],
1254 'object' => ['id' => $id, 'type' => 'Follow',
1255 'actor' => $profile['url'],
1256 'object' => $owner['url']],
1257 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1258 'to' => [$profile['url']]];
1260 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1262 $signed = LDSignature::sign($data, $owner);
1263 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1267 * Transmits a message that we don't want to follow this contact anymore
1269 * @param string $target Target profile
1270 * @param integer $cid Contact ID of target
1271 * @param integer $uid User ID
1273 public static function sendContactUndo($target, $cid, $uid)
1275 $profile = APContact::getByURL($target);
1277 $object_id = self::activityIDFromContact($cid);
1278 if (empty($object_id)) {
1282 $id = System::baseUrl() . '/activity/' . System::createGUID();
1284 $owner = User::getOwnerDataById($uid);
1285 $data = ['@context' => ActivityPub::CONTEXT,
1288 'actor' => $owner['url'],
1289 'object' => ['id' => $object_id, 'type' => 'Follow',
1290 'actor' => $owner['url'],
1291 'object' => $profile['url']],
1292 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1293 'to' => [$profile['url']]];
1295 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1297 $signed = LDSignature::sign($data, $owner);
1298 HTTPSignature::transmit($signed, $profile['inbox'], $uid);