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 ($receiver == $item_profile['followers']) {
502 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
504 $profile = APContact::getByURL($receiver, false);
505 if (!empty($profile)) {
506 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
507 $target = $profile['inbox'];
509 $target = $profile['sharedinbox'];
511 $inboxes[$target] = $target;
521 * Returns the activity type of a given item
525 * @return string with activity type
527 private static function getTypeOfItem($item)
529 if (!empty(Diaspora::isReshare($item['body'], false))) {
531 } elseif ($item['verb'] == ACTIVITY_POST) {
532 if ($item['created'] == $item['edited']) {
537 } elseif ($item['verb'] == ACTIVITY_LIKE) {
539 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
541 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
543 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
545 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
546 $type = 'TentativeAccept';
555 * Creates the activity or fetches it from the cache
557 * @param integer $item_id
558 * @param boolean $force Force new cache entry
560 * @return array with the activity
562 public static function createCachedActivityFromItem($item_id, $force = false)
564 $cachekey = 'APDelivery:createActivity:' . $item_id;
567 $data = Cache::get($cachekey);
568 if (!is_null($data)) {
573 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
575 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
580 * Creates an activity array for a given item id
582 * @param integer $item_id
583 * @param boolean $object_mode Is the activity item is used inside another object?
585 * @return array of activity
587 public static function createActivityFromItem($item_id, $object_mode = false)
589 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
591 if (!DBA::isResult($item)) {
595 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
596 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
597 if (DBA::isResult($conversation)) {
598 $data = json_decode($conversation['source']);
604 $type = self::getTypeOfItem($item);
607 $data = ['@context' => ActivityPub::CONTEXT];
609 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
611 } elseif ($item['deleted']) {
618 $data['id'] = $item['uri'] . '#' . $type;
619 $data['type'] = $type;
620 $data['actor'] = $item['owner-link'];
622 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
624 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
626 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
628 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
629 $data['object'] = self::createNote($item);
630 } elseif ($data['type'] == 'Announce') {
631 $data['object'] = self::createAnnounce($item);
632 } elseif ($data['type'] == 'Undo') {
633 $data['object'] = self::createActivityFromItem($item_id, true);
635 $data['diaspora:guid'] = $item['guid'];
636 if (!empty($item['signed_text'])) {
637 $data['diaspora:like'] = $item['signed_text'];
639 $data['object'] = $item['thr-parent'];
642 $owner = User::getOwnerDataById($item['uid']);
645 return LDSignature::sign($data, $owner);
650 /// @todo Create "conversation" entry
654 * Creates an object array for a given item id
656 * @param integer $item_id
658 * @return array with the object data
660 public static function createObjectFromItemID($item_id)
662 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
664 if (!DBA::isResult($item)) {
668 $data = ['@context' => ActivityPub::CONTEXT];
669 $data = array_merge($data, self::createNote($item));
675 * Creates a location entry for a given item array
679 * @return array with location array
681 private static function createLocation($item)
683 $location = ['type' => 'Place'];
685 if (!empty($item['location'])) {
686 $location['name'] = $item['location'];
691 if (empty($item['coord'])) {
692 $coord = Map::getCoordinates($item['location']);
694 $coords = explode(' ', $item['coord']);
695 if (count($coords) == 2) {
696 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
700 if (!empty($coord['lat']) && !empty($coord['lon'])) {
701 $location['latitude'] = $coord['lat'];
702 $location['longitude'] = $coord['lon'];
709 * Returns a tag array for a given item array
713 * @return array of tags
715 private static function createTagList($item)
719 $terms = Term::tagArrayFromItemId($item['id']);
720 foreach ($terms as $term) {
721 if ($term['type'] == TERM_HASHTAG) {
722 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
723 } elseif ($term['type'] == TERM_MENTION) {
724 $contact = Contact::getDetailsByURL($term['url']);
725 if (!empty($contact['addr'])) {
726 $mention = '@' . $contact['addr'];
728 $mention = '@' . $term['url'];
731 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
738 * Adds attachment data to the JSON document
740 * @param array $item Data of the item that is to be posted
741 * @param text $type Object type
743 * @return array with attachment data
745 private static function createAttachmentList($item, $type)
749 $arr = explode('[/attach],', $item['attach']);
751 foreach ($arr as $r) {
753 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
755 $attributes = ['type' => 'Document',
756 'mediaType' => $matches[3],
757 'url' => $matches[1],
760 if (trim($matches[4]) != '') {
761 $attributes['name'] = trim($matches[4]);
764 $attachments[] = $attributes;
769 if ($type != 'Note') {
773 // Simplify image codes
774 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
776 // Grab all pictures and create attachments out of them
777 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
778 foreach ($pictures[1] as $picture) {
779 $imgdata = Image::getInfoFromURL($picture);
781 $attachments[] = ['type' => 'Document',
782 'mediaType' => $imgdata['mime'],
793 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
795 * @param array $match Matching values for the callback
796 * @return string Replaced mention
798 private static function mentionCallback($match)
800 if (empty($match[1])) {
804 $data = Contact::getDetailsByURL($match[1]);
805 if (empty($data) || empty($data['nick'])) {
809 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
813 * Remove image elements and replaces them with links to the image
815 * @param string $body
817 * @return string with replaced elements
819 private static function removePictures($body)
821 // Simplify image codes
822 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
824 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
825 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
831 * Fetches the "context" value for a givem item array from the "conversation" table
835 * @return string with context url
837 private static function fetchContextURLForItem($item)
839 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
840 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
841 $context_uri = $conversation['conversation-href'];
842 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
843 $context_uri = $conversation['conversation-uri'];
845 $context_uri = $item['parent-uri'] . '#context';
851 * Returns if the post contains sensitive content ("nsfw")
853 * @param integer $item_id
857 private static function isSensitive($item_id)
859 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
860 return DBA::exists('term', $condition);
868 * @return array with the event data
870 public static function createEvent($item)
873 $event['name'] = $item['event-summary'];
874 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
875 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
877 if (!$item['event-nofinish']) {
878 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
881 if (!empty($item['event-location'])) {
882 $item['location'] = $item['event-location'];
883 $event['location'] = self::createLocation($item);
890 * Creates a note/article object array
894 * @return array with the object data
896 public static function createNote($item)
898 if ($item['event-type'] == 'event') {
900 } elseif (!empty($item['title'])) {
906 if ($item['deleted']) {
911 $data['id'] = $item['uri'];
912 $data['type'] = $type;
914 if ($item['deleted']) {
918 $data['summary'] = null; // Ignore by now
920 if ($item['uri'] != $item['thr-parent']) {
921 $data['inReplyTo'] = $item['thr-parent'];
923 $data['inReplyTo'] = null;
926 $data['diaspora:guid'] = $item['guid'];
927 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
929 if ($item['created'] != $item['edited']) {
930 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
933 $data['url'] = $item['plink'];
934 $data['attributedTo'] = $item['author-link'];
935 $data['sensitive'] = self::isSensitive($item['id']);
936 $data['context'] = self::fetchContextURLForItem($item);
938 if (!empty($item['title'])) {
939 $data['name'] = BBCode::toPlaintext($item['title'], false);
942 $body = $item['body'];
944 if ($type == 'Note') {
945 $body = self::removePictures($body);
948 if ($type == 'Event') {
949 $data = array_merge($data, self::createEvent($item));
951 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
952 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
954 $data['content'] = BBCode::convert($body, false, 7);
957 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
959 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
960 $data['diaspora:comment'] = $item['signed_text'];
963 $data['attachment'] = self::createAttachmentList($item, $type);
964 $data['tag'] = self::createTagList($item);
966 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
967 $data['location'] = self::createLocation($item);
970 if (!empty($item['app'])) {
971 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
974 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
980 * Creates an announce object entry
984 * @return string with announced object url
986 public static function createAnnounce($item)
988 $announce = api_share_as_retweet($item);
989 if (empty($announce['plink'])) {
990 return self::createNote($item);
993 return $announce['plink'];
997 * Transmits a contact suggestion to a given inbox
999 * @param integer $uid User ID
1000 * @param string $inbox Target inbox
1001 * @param integer $suggestion_id Suggestion ID
1003 * @return boolean was the transmission successful?
1005 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1007 $owner = User::getOwnerDataById($uid);
1009 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1011 $data = ['@context' => ActivityPub::CONTEXT,
1012 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1013 'type' => 'Announce',
1014 'actor' => $owner['url'],
1015 'object' => $suggestion['url'],
1016 'content' => $suggestion['note'],
1017 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1018 'to' => [ActivityPub::PUBLIC_COLLECTION],
1021 $signed = LDSignature::sign($data, $owner);
1023 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1024 return HTTPSignature::transmit($signed, $inbox, $uid);
1028 * Transmits a profile relocation to a given inbox
1030 * @param integer $uid User ID
1031 * @param string $inbox Target inbox
1033 * @return boolean was the transmission successful?
1035 public static function sendProfileRelocation($uid, $inbox)
1037 $owner = User::getOwnerDataById($uid);
1039 $data = ['@context' => ActivityPub::CONTEXT,
1040 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1041 'type' => 'dfrn:relocate',
1042 'actor' => $owner['url'],
1043 'object' => $owner['url'],
1044 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1045 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1046 'to' => [ActivityPub::PUBLIC_COLLECTION],
1049 $signed = LDSignature::sign($data, $owner);
1051 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1052 return HTTPSignature::transmit($signed, $inbox, $uid);
1056 * Transmits a profile deletion to a given inbox
1058 * @param integer $uid User ID
1059 * @param string $inbox Target inbox
1061 * @return boolean was the transmission successful?
1063 public static function sendProfileDeletion($uid, $inbox)
1065 $owner = User::getOwnerDataById($uid);
1067 $data = ['@context' => ActivityPub::CONTEXT,
1068 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1070 'actor' => $owner['url'],
1071 'object' => $owner['url'],
1072 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1073 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1074 'to' => [ActivityPub::PUBLIC_COLLECTION],
1077 $signed = LDSignature::sign($data, $owner);
1079 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1080 return HTTPSignature::transmit($signed, $inbox, $uid);
1084 * Transmits a profile change to a given inbox
1086 * @param integer $uid User ID
1087 * @param string $inbox Target inbox
1089 * @return boolean was the transmission successful?
1091 public static function sendProfileUpdate($uid, $inbox)
1093 $owner = User::getOwnerDataById($uid);
1094 $profile = APContact::getByURL($owner['url']);
1096 $data = ['@context' => ActivityPub::CONTEXT,
1097 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1099 'actor' => $owner['url'],
1100 'object' => self::getProfile($uid),
1101 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1102 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1103 'to' => [$profile['followers']],
1106 $signed = LDSignature::sign($data, $owner);
1108 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1109 return HTTPSignature::transmit($signed, $inbox, $uid);
1113 * Transmits a given activity to a target
1115 * @param array $activity
1116 * @param string $target Target profile
1117 * @param integer $uid User ID
1119 public static function sendActivity($activity, $target, $uid)
1121 $profile = APContact::getByURL($target);
1123 $owner = User::getOwnerDataById($uid);
1125 $data = ['@context' => ActivityPub::CONTEXT,
1126 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1127 'type' => $activity,
1128 'actor' => $owner['url'],
1129 'object' => $profile['url'],
1130 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1131 'to' => $profile['url']];
1133 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1135 $signed = LDSignature::sign($data, $owner);
1136 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1140 * Transmit a message that the contact request had been accepted
1142 * @param string $target Target profile
1144 * @param integer $uid User ID
1146 public static function sendContactAccept($target, $id, $uid)
1148 $profile = APContact::getByURL($target);
1150 $owner = User::getOwnerDataById($uid);
1151 $data = ['@context' => ActivityPub::CONTEXT,
1152 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1154 'actor' => $owner['url'],
1155 'object' => ['id' => $id, 'type' => 'Follow',
1156 'actor' => $profile['url'],
1157 'object' => $owner['url']],
1158 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1159 'to' => $profile['url']];
1161 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1163 $signed = LDSignature::sign($data, $owner);
1164 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1168 * Reject a contact request or terminates the contact relation
1170 * @param string $target Target profile
1172 * @param integer $uid User ID
1174 public static function sendContactReject($target, $id, $uid)
1176 $profile = APContact::getByURL($target);
1178 $owner = User::getOwnerDataById($uid);
1179 $data = ['@context' => ActivityPub::CONTEXT,
1180 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1182 'actor' => $owner['url'],
1183 'object' => ['id' => $id, 'type' => 'Follow',
1184 'actor' => $profile['url'],
1185 'object' => $owner['url']],
1186 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1187 'to' => $profile['url']];
1189 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1191 $signed = LDSignature::sign($data, $owner);
1192 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1196 * Transmits a message that we don't want to follow this contact anymore
1198 * @param string $target Target profile
1199 * @param integer $uid User ID
1201 public static function sendContactUndo($target, $uid)
1203 $profile = APContact::getByURL($target);
1205 $id = System::baseUrl() . '/activity/' . System::createGUID();
1207 $owner = User::getOwnerDataById($uid);
1208 $data = ['@context' => ActivityPub::CONTEXT,
1211 'actor' => $owner['url'],
1212 'object' => ['id' => $id, 'type' => 'Follow',
1213 'actor' => $owner['url'],
1214 'object' => $profile['url']],
1215 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1216 'to' => $profile['url']];
1218 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1220 $signed = LDSignature::sign($data, $owner);
1221 HTTPSignature::transmit($signed, $profile['inbox'], $uid);