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, '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, '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
301 * @return array with permission data
303 private static function createPermissionBlockForItem($item, $blindcopy)
305 // Will be activated in a later step
306 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
308 // For now only send to these contacts:
309 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
311 $data = ['to' => [], 'cc' => [], 'bcc' => []];
313 $actor_profile = APContact::getByURL($item['author-link']);
315 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
317 if (!$item['private']) {
318 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
320 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
321 if (!empty($actor_profile['followers'])) {
322 $data['cc'][] = $actor_profile['followers'];
325 foreach ($terms as $term) {
326 $profile = APContact::getByURL($term['url'], false);
327 if (!empty($profile)) {
328 $data['to'][] = $profile['url'];
332 $receiver_list = Item::enumeratePermissions($item);
336 foreach ($terms as $term) {
337 $cid = Contact::getIdForURL($term['url'], $item['uid']);
338 if (!empty($cid) && in_array($cid, $receiver_list)) {
339 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
340 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
341 $data['to'][] = $profile['url'];
346 foreach ($receiver_list as $receiver) {
347 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => $networks]);
348 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
349 // BCC is currently deactivated, due to Pleroma and Mastodon not reacting like expected
350 // $data['bcc'][] = $profile['url'];
351 $data['cc'][] = $profile['url'];
356 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
357 while ($parent = Item::fetch($parents)) {
358 // Don't include data from future posts
359 if ($parent['id'] >= $item['id']) {
363 $profile = APContact::getByURL($parent['author-link'], false);
364 if (!empty($profile)) {
365 if ($parent['uri'] == $item['thr-parent']) {
366 $data['to'][] = $profile['url'];
368 $data['cc'][] = $profile['url'];
372 if ($item['gravity'] != GRAVITY_PARENT) {
376 $profile = APContact::getByURL($parent['owner-link'], false);
377 if (!empty($profile)) {
378 $data['cc'][] = $profile['url'];
381 DBA::close($parents);
383 $data['to'] = array_unique($data['to']);
384 $data['cc'] = array_unique($data['cc']);
385 $data['bcc'] = array_unique($data['bcc']);
387 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
388 unset($data['to'][$key]);
391 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
392 unset($data['cc'][$key]);
395 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
396 unset($data['bcc'][$key]);
399 foreach ($data['to'] as $to) {
400 if (($key = array_search($to, $data['cc'])) !== false) {
401 unset($data['cc'][$key]);
404 if (($key = array_search($to, $data['bcc'])) !== false) {
405 unset($data['bcc'][$key]);
409 foreach ($data['cc'] as $cc) {
410 if (($key = array_search($cc, $data['bcc'])) !== false) {
411 unset($data['bcc'][$key]);
415 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
418 unset($receivers['bcc']);
425 * Fetches a list of inboxes of followers of a given user
427 * @param integer $uid User ID
428 * @param boolean $personal fetch personal inboxes
430 * @return array of follower inboxes
432 public static function fetchTargetInboxesforUser($uid, $personal = false)
436 // Will be activated in a later step
437 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
439 // For now only send to these contacts:
440 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
442 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
445 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
448 $contacts = DBA::select('contact', ['url'], $condition);
449 while ($contact = DBA::fetch($contacts)) {
450 if (Network::isUrlBlocked($contact['url'])) {
454 $profile = APContact::getByURL($contact['url'], false);
455 if (!empty($profile)) {
456 if (empty($profile['sharedinbox']) || $personal) {
457 $target = $profile['inbox'];
459 $target = $profile['sharedinbox'];
461 $inboxes[$target] = $target;
464 DBA::close($contacts);
470 * Fetches an array of inboxes for the given item and user
473 * @param integer $uid User ID
474 * @param boolean $personal fetch personal inboxes
476 * @return array with inboxes
478 public static function fetchTargetInboxes($item, $uid, $personal = false)
480 $permissions = self::createPermissionBlockForItem($item, true);
481 if (empty($permissions)) {
487 if ($item['gravity'] == GRAVITY_ACTIVITY) {
488 $item_profile = APContact::getByURL($item['author-link'], false);
490 $item_profile = APContact::getByURL($item['owner-link'], false);
493 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
494 if (empty($permissions[$element])) {
498 $blindcopy = in_array($element, ['bto', 'bcc']);
500 foreach ($permissions[$element] as $receiver) {
501 if (Network::isUrlBlocked($receiver)) {
505 if ($receiver == $item_profile['followers']) {
506 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
508 $profile = APContact::getByURL($receiver, false);
509 if (!empty($profile)) {
510 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
511 $target = $profile['inbox'];
513 $target = $profile['sharedinbox'];
515 $inboxes[$target] = $target;
525 * Returns the activity type of a given item
529 * @return string with activity type
531 private static function getTypeOfItem($item)
533 if (!empty(Diaspora::isReshare($item['body'], false))) {
535 } elseif ($item['verb'] == ACTIVITY_POST) {
536 if ($item['created'] == $item['edited']) {
541 } elseif ($item['verb'] == ACTIVITY_LIKE) {
543 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
545 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
547 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
549 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
550 $type = 'TentativeAccept';
559 * Creates the activity or fetches it from the cache
561 * @param integer $item_id
562 * @param boolean $force Force new cache entry
564 * @return array with the activity
566 public static function createCachedActivityFromItem($item_id, $force = false)
568 $cachekey = 'APDelivery:createActivity:' . $item_id;
571 $data = Cache::get($cachekey);
572 if (!is_null($data)) {
577 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
579 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
584 * Creates an activity array for a given item id
586 * @param integer $item_id
587 * @param boolean $object_mode Is the activity item is used inside another object?
589 * @return array of activity
591 public static function createActivityFromItem($item_id, $object_mode = false)
593 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
595 if (!DBA::isResult($item)) {
599 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
600 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
601 if (DBA::isResult($conversation)) {
602 $data = json_decode($conversation['source']);
608 $type = self::getTypeOfItem($item);
611 $data = ['@context' => ActivityPub::CONTEXT];
613 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
615 } elseif ($item['deleted']) {
622 $data['id'] = $item['uri'] . '#' . $type;
623 $data['type'] = $type;
624 $data['actor'] = $item['owner-link'];
626 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
628 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
630 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
632 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
633 $data['object'] = self::createNote($item);
634 } elseif ($data['type'] == 'Announce') {
635 $data['object'] = self::createAnnounce($item);
636 } elseif ($data['type'] == 'Undo') {
637 $data['object'] = self::createActivityFromItem($item_id, true);
639 $data['diaspora:guid'] = $item['guid'];
640 if (!empty($item['signed_text'])) {
641 $data['diaspora:like'] = $item['signed_text'];
643 $data['object'] = $item['thr-parent'];
646 $owner = User::getOwnerDataById($item['uid']);
649 return LDSignature::sign($data, $owner);
654 /// @todo Create "conversation" entry
658 * Creates an object array for a given item id
660 * @param integer $item_id
662 * @return array with the object data
664 public static function createObjectFromItemID($item_id)
666 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
668 if (!DBA::isResult($item)) {
672 $data = ['@context' => ActivityPub::CONTEXT];
673 $data = array_merge($data, self::createNote($item));
679 * Creates a location entry for a given item array
683 * @return array with location array
685 private static function createLocation($item)
687 $location = ['type' => 'Place'];
689 if (!empty($item['location'])) {
690 $location['name'] = $item['location'];
695 if (empty($item['coord'])) {
696 $coord = Map::getCoordinates($item['location']);
698 $coords = explode(' ', $item['coord']);
699 if (count($coords) == 2) {
700 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
704 if (!empty($coord['lat']) && !empty($coord['lon'])) {
705 $location['latitude'] = $coord['lat'];
706 $location['longitude'] = $coord['lon'];
713 * Returns a tag array for a given item array
717 * @return array of tags
719 private static function createTagList($item)
723 $terms = Term::tagArrayFromItemId($item['id']);
724 foreach ($terms as $term) {
725 if ($term['type'] == TERM_HASHTAG) {
726 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
727 } elseif ($term['type'] == TERM_MENTION) {
728 $contact = Contact::getDetailsByURL($term['url']);
729 if (!empty($contact['addr'])) {
730 $mention = '@' . $contact['addr'];
732 $mention = '@' . $term['url'];
735 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
742 * Adds attachment data to the JSON document
744 * @param array $item Data of the item that is to be posted
745 * @param text $type Object type
747 * @return array with attachment data
749 private static function createAttachmentList($item, $type)
753 $arr = explode('[/attach],', $item['attach']);
755 foreach ($arr as $r) {
757 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
759 $attributes = ['type' => 'Document',
760 'mediaType' => $matches[3],
761 'url' => $matches[1],
764 if (trim($matches[4]) != '') {
765 $attributes['name'] = trim($matches[4]);
768 $attachments[] = $attributes;
773 if ($type != 'Note') {
777 // Simplify image codes
778 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
780 // Grab all pictures and create attachments out of them
781 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
782 foreach ($pictures[1] as $picture) {
783 $imgdata = Image::getInfoFromURL($picture);
785 $attachments[] = ['type' => 'Document',
786 'mediaType' => $imgdata['mime'],
797 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
799 * @param array $match Matching values for the callback
800 * @return string Replaced mention
802 private static function mentionCallback($match)
804 if (empty($match[1])) {
808 $data = Contact::getDetailsByURL($match[1]);
809 if (empty($data) || empty($data['nick'])) {
813 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
817 * Remove image elements and replaces them with links to the image
819 * @param string $body
821 * @return string with replaced elements
823 private static function removePictures($body)
825 // Simplify image codes
826 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
828 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
829 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
835 * Fetches the "context" value for a givem item array from the "conversation" table
839 * @return string with context url
841 private static function fetchContextURLForItem($item)
843 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
844 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
845 $context_uri = $conversation['conversation-href'];
846 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
847 $context_uri = $conversation['conversation-uri'];
849 $context_uri = $item['parent-uri'] . '#context';
855 * Returns if the post contains sensitive content ("nsfw")
857 * @param integer $item_id
861 private static function isSensitive($item_id)
863 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
864 return DBA::exists('term', $condition);
872 * @return array with the event data
874 public static function createEvent($item)
877 $event['name'] = $item['event-summary'];
878 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
879 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
881 if (!$item['event-nofinish']) {
882 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
885 if (!empty($item['event-location'])) {
886 $item['location'] = $item['event-location'];
887 $event['location'] = self::createLocation($item);
894 * Creates a note/article object array
898 * @return array with the object data
900 public static function createNote($item)
902 if ($item['event-type'] == 'event') {
904 } elseif (!empty($item['title'])) {
910 if ($item['deleted']) {
915 $data['id'] = $item['uri'];
916 $data['type'] = $type;
918 if ($item['deleted']) {
922 $data['summary'] = null; // Ignore by now
924 if ($item['uri'] != $item['thr-parent']) {
925 $data['inReplyTo'] = $item['thr-parent'];
927 $data['inReplyTo'] = null;
930 $data['diaspora:guid'] = $item['guid'];
931 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
933 if ($item['created'] != $item['edited']) {
934 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
937 $data['url'] = $item['plink'];
938 $data['attributedTo'] = $item['author-link'];
939 $data['sensitive'] = self::isSensitive($item['id']);
940 $data['context'] = self::fetchContextURLForItem($item);
942 if (!empty($item['title'])) {
943 $data['name'] = BBCode::toPlaintext($item['title'], false);
946 $body = $item['body'];
948 if ($type == 'Note') {
949 $body = self::removePictures($body);
952 if ($type == 'Event') {
953 $data = array_merge($data, self::createEvent($item));
955 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
956 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
958 $data['content'] = BBCode::convert($body, false, 7);
961 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
963 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
964 $data['diaspora:comment'] = $item['signed_text'];
967 $data['attachment'] = self::createAttachmentList($item, $type);
968 $data['tag'] = self::createTagList($item);
970 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
971 $data['location'] = self::createLocation($item);
974 if (!empty($item['app'])) {
975 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
978 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
984 * Creates an announce object entry
988 * @return string with announced object url
990 public static function createAnnounce($item)
992 $announce = api_share_as_retweet($item);
993 if (empty($announce['plink'])) {
994 return self::createNote($item);
997 return $announce['plink'];
1001 * Transmits a contact suggestion to a given inbox
1003 * @param integer $uid User ID
1004 * @param string $inbox Target inbox
1005 * @param integer $suggestion_id Suggestion ID
1007 * @return boolean was the transmission successful?
1009 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1011 $owner = User::getOwnerDataById($uid);
1013 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1015 $data = ['@context' => ActivityPub::CONTEXT,
1016 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1017 'type' => 'Announce',
1018 'actor' => $owner['url'],
1019 'object' => $suggestion['url'],
1020 'content' => $suggestion['note'],
1021 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1022 'to' => [ActivityPub::PUBLIC_COLLECTION],
1025 $signed = LDSignature::sign($data, $owner);
1027 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1028 return HTTPSignature::transmit($signed, $inbox, $uid);
1032 * Transmits a profile relocation to a given inbox
1034 * @param integer $uid User ID
1035 * @param string $inbox Target inbox
1037 * @return boolean was the transmission successful?
1039 public static function sendProfileRelocation($uid, $inbox)
1041 $owner = User::getOwnerDataById($uid);
1043 $data = ['@context' => ActivityPub::CONTEXT,
1044 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1045 'type' => 'dfrn:relocate',
1046 'actor' => $owner['url'],
1047 'object' => $owner['url'],
1048 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1049 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1050 'to' => [ActivityPub::PUBLIC_COLLECTION],
1053 $signed = LDSignature::sign($data, $owner);
1055 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1056 return HTTPSignature::transmit($signed, $inbox, $uid);
1060 * Transmits a profile deletion to a given inbox
1062 * @param integer $uid User ID
1063 * @param string $inbox Target inbox
1065 * @return boolean was the transmission successful?
1067 public static function sendProfileDeletion($uid, $inbox)
1069 $owner = User::getOwnerDataById($uid);
1071 $data = ['@context' => ActivityPub::CONTEXT,
1072 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1074 'actor' => $owner['url'],
1075 'object' => $owner['url'],
1076 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1077 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1078 'to' => [ActivityPub::PUBLIC_COLLECTION],
1081 $signed = LDSignature::sign($data, $owner);
1083 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1084 return HTTPSignature::transmit($signed, $inbox, $uid);
1088 * Transmits a profile change to a given inbox
1090 * @param integer $uid User ID
1091 * @param string $inbox Target inbox
1093 * @return boolean was the transmission successful?
1095 public static function sendProfileUpdate($uid, $inbox)
1097 $owner = User::getOwnerDataById($uid);
1098 $profile = APContact::getByURL($owner['url']);
1100 $data = ['@context' => ActivityPub::CONTEXT,
1101 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1103 'actor' => $owner['url'],
1104 'object' => self::getProfile($uid),
1105 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1106 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1107 'to' => [$profile['followers']],
1110 $signed = LDSignature::sign($data, $owner);
1112 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1113 return HTTPSignature::transmit($signed, $inbox, $uid);
1117 * Transmits a given activity to a target
1119 * @param array $activity
1120 * @param string $target Target profile
1121 * @param integer $uid User ID
1123 public static function sendActivity($activity, $target, $uid)
1125 $profile = APContact::getByURL($target);
1127 $owner = User::getOwnerDataById($uid);
1129 $data = ['@context' => ActivityPub::CONTEXT,
1130 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1131 'type' => $activity,
1132 'actor' => $owner['url'],
1133 'object' => $profile['url'],
1134 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1135 'to' => $profile['url']];
1137 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1139 $signed = LDSignature::sign($data, $owner);
1140 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1144 * Transmit a message that the contact request had been accepted
1146 * @param string $target Target profile
1148 * @param integer $uid User ID
1150 public static function sendContactAccept($target, $id, $uid)
1152 $profile = APContact::getByURL($target);
1154 $owner = User::getOwnerDataById($uid);
1155 $data = ['@context' => ActivityPub::CONTEXT,
1156 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1158 'actor' => $owner['url'],
1159 'object' => ['id' => $id, 'type' => 'Follow',
1160 'actor' => $profile['url'],
1161 'object' => $owner['url']],
1162 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1163 'to' => $profile['url']];
1165 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1167 $signed = LDSignature::sign($data, $owner);
1168 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1172 * Reject a contact request or terminates the contact relation
1174 * @param string $target Target profile
1176 * @param integer $uid User ID
1178 public static function sendContactReject($target, $id, $uid)
1180 $profile = APContact::getByURL($target);
1182 $owner = User::getOwnerDataById($uid);
1183 $data = ['@context' => ActivityPub::CONTEXT,
1184 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1186 'actor' => $owner['url'],
1187 'object' => ['id' => $id, 'type' => 'Follow',
1188 'actor' => $profile['url'],
1189 'object' => $owner['url']],
1190 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1191 'to' => $profile['url']];
1193 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1195 $signed = LDSignature::sign($data, $owner);
1196 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1200 * Transmits a message that we don't want to follow this contact anymore
1202 * @param string $target Target profile
1203 * @param integer $uid User ID
1205 public static function sendContactUndo($target, $uid)
1207 $profile = APContact::getByURL($target);
1209 $id = System::baseUrl() . '/activity/' . System::createGUID();
1211 $owner = User::getOwnerDataById($uid);
1212 $data = ['@context' => ActivityPub::CONTEXT,
1215 'actor' => $owner['url'],
1216 'object' => ['id' => $id, 'type' => 'Follow',
1217 'actor' => $owner['url'],
1218 'object' => $profile['url']],
1219 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1220 'to' => $profile['url']];
1222 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1224 $signed = LDSignature::sign($data, $owner);
1225 HTTPSignature::transmit($signed, $profile['inbox'], $uid);