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\Object\Image;
25 use Friendica\Protocol\ActivityPub;
26 use Friendica\Core\Cache;
27 use Friendica\Util\Map;
28 use Friendica\Util\Network;
30 require_once 'include/api.php';
31 require_once 'mod/share.php';
34 * @brief ActivityPub Transmitter Protocol class
42 * collects the lost of followers of the given owner
44 * @param array $owner Owner array
45 * @param integer $page Page number
47 * @return array of owners
48 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
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
96 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
98 public static function getFollowing($owner, $page = null)
100 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
101 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
102 $count = DBA::count('contact', $condition);
104 $data = ['@context' => ActivityPub::CONTEXT];
105 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
106 $data['type'] = 'OrderedCollection';
107 $data['totalItems'] = $count;
109 // When we hide our friends we will only show the pure number but don't allow more.
110 $profile = Profile::getByUID($owner['uid']);
111 if (!empty($profile['hide-friends'])) {
116 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
120 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
121 while ($contact = DBA::fetch($contacts)) {
122 $list[] = $contact['url'];
126 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
129 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
131 $data['orderedItems'] = $list;
138 * Public posts for the given owner
140 * @param array $owner Owner array
141 * @param integer $page Page numbe
143 * @return array of posts
144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
145 * @throws \ImagickException
147 public static function getOutbox($owner, $page = null)
149 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
151 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
152 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
153 'deleted' => false, 'visible' => true];
154 $count = DBA::count('item', $condition);
156 $data = ['@context' => ActivityPub::CONTEXT];
157 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
158 $data['type'] = 'OrderedCollection';
159 $data['totalItems'] = $count;
162 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
166 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
168 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
169 while ($item = Item::fetch($items)) {
170 $object = self::createObjectFromItemID($item['id']);
171 unset($object['@context']);
176 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
179 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
181 $data['orderedItems'] = $list;
188 * Return the ActivityPub profile of the given user
190 * @param integer $uid User ID
191 * @return array with profile data
192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
194 public static function getProfile($uid)
196 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
197 'account_removed' => false, 'verified' => true];
198 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
199 $user = DBA::selectFirst('user', $fields, $condition);
200 if (!DBA::isResult($user)) {
204 $fields = ['locality', 'region', 'country-name'];
205 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
206 if (!DBA::isResult($profile)) {
210 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
211 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
212 if (!DBA::isResult($contact)) {
216 // On old installations and never changed contacts this might not be filled
217 if (empty($contact['avatar'])) {
218 $contact['avatar'] = $contact['photo'];
221 $data = ['@context' => ActivityPub::CONTEXT];
222 $data['id'] = $contact['url'];
223 $data['diaspora:guid'] = $user['guid'];
224 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
225 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
226 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
227 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
228 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
229 $data['preferredUsername'] = $user['nickname'];
230 $data['name'] = $contact['name'];
231 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
232 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
233 $data['summary'] = $contact['about'];
234 $data['url'] = $contact['url'];
235 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
236 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
237 'owner' => $contact['url'],
238 'publicKeyPem' => $user['pubkey']];
239 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
240 $data['icon'] = ['type' => 'Image',
241 'url' => $contact['avatar']];
243 // tags: https://kitty.town/@inmysocks/100656097926961126.json
248 * Returns an array with permissions of a given item array
252 * @return array with permissions
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 * @throws \ImagickException
256 private static function fetchPermissionBlockFromConversation($item)
258 if (empty($item['thr-parent'])) {
262 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
263 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
264 if (!DBA::isResult($conversation)) {
268 $activity = json_decode($conversation['source'], true);
270 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
271 $profile = APContact::getByURL($actor);
273 $item_profile = APContact::getByURL($item['author-link']);
274 $exclude[] = $item['author-link'];
276 if ($item['gravity'] == GRAVITY_PARENT) {
277 $exclude[] = $item['owner-link'];
280 $permissions['to'][] = $actor;
282 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
283 if (empty($activity[$element])) {
286 if (is_string($activity[$element])) {
287 $activity[$element] = [$activity[$element]];
290 foreach ($activity[$element] as $receiver) {
291 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
292 $permissions[$element][] = $item_profile['followers'];
293 } elseif (!in_array($receiver, $exclude)) {
294 $permissions[$element][] = $receiver;
302 * Creates an array of permissions from an item thread
305 * @param boolean $blindcopy
306 * @param boolean $last_id
308 * @return array with permission data
309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
310 * @throws \ImagickException
312 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
315 $last_id = $item['id'];
320 // Check if we should always deliver our stuff via BCC
321 if (!empty($item['uid'])) {
322 $profile = Profile::getByUID($item['uid']);
323 if (!empty($profile)) {
324 $always_bcc = $profile['hide-friends'];
328 if (Config::get('debug', 'total_ap_delivery')) {
329 // Will be activated in a later step
330 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
332 // For now only send to these contacts:
333 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
336 $data = ['to' => [], 'cc' => [], 'bcc' => []];
338 if ($item['gravity'] == GRAVITY_PARENT) {
339 $actor_profile = APContact::getByURL($item['owner-link']);
341 $actor_profile = APContact::getByURL($item['author-link']);
344 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
346 if (!$item['private']) {
347 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
349 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
351 foreach ($terms as $term) {
352 $profile = APContact::getByURL($term['url'], false);
353 if (!empty($profile)) {
354 $data['to'][] = $profile['url'];
358 $receiver_list = Item::enumeratePermissions($item);
360 foreach ($terms as $term) {
361 $cid = Contact::getIdForURL($term['url'], $item['uid']);
362 if (!empty($cid) && in_array($cid, $receiver_list)) {
363 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
364 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
365 $data['to'][] = $profile['url'];
370 foreach ($receiver_list as $receiver) {
371 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
372 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
373 if ($contact['hidden'] || $always_bcc) {
374 $data['bcc'][] = $profile['url'];
376 $data['cc'][] = $profile['url'];
382 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
383 while ($parent = Item::fetch($parents)) {
384 if ($parent['gravity'] == GRAVITY_PARENT) {
385 $profile = APContact::getByURL($parent['owner-link'], false);
386 if (!empty($profile)) {
387 if ($item['gravity'] != GRAVITY_PARENT) {
388 // Comments to forums are directed to the forum
389 // But comments to forums aren't directed to the followers collection
390 if ($profile['type'] == 'Group') {
391 $data['to'][] = $profile['url'];
393 $data['cc'][] = $profile['url'];
394 if (!$item['private']) {
395 $data['cc'][] = $actor_profile['followers'];
399 // Public thread parent post always are directed to the followes
400 if (!$item['private']) {
401 $data['cc'][] = $actor_profile['followers'];
407 // Don't include data from future posts
408 if ($parent['id'] >= $last_id) {
412 $profile = APContact::getByURL($parent['author-link'], false);
413 if (!empty($profile)) {
414 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
415 $data['to'][] = $profile['url'];
417 $data['cc'][] = $profile['url'];
421 DBA::close($parents);
423 $data['to'] = array_unique($data['to']);
424 $data['cc'] = array_unique($data['cc']);
425 $data['bcc'] = array_unique($data['bcc']);
427 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
428 unset($data['to'][$key]);
431 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
432 unset($data['cc'][$key]);
435 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
436 unset($data['bcc'][$key]);
439 foreach ($data['to'] as $to) {
440 if (($key = array_search($to, $data['cc'])) !== false) {
441 unset($data['cc'][$key]);
444 if (($key = array_search($to, $data['bcc'])) !== false) {
445 unset($data['bcc'][$key]);
449 foreach ($data['cc'] as $cc) {
450 if (($key = array_search($cc, $data['bcc'])) !== false) {
451 unset($data['bcc'][$key]);
455 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
458 unset($receivers['bcc']);
465 * Fetches a list of inboxes of followers of a given user
467 * @param integer $uid User ID
468 * @param boolean $personal fetch personal inboxes
470 * @return array of follower inboxes
471 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
472 * @throws \ImagickException
474 public static function fetchTargetInboxesforUser($uid, $personal = false)
478 if (Config::get('debug', 'total_ap_delivery')) {
479 // Will be activated in a later step
480 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
482 // For now only send to these contacts:
483 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
486 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
489 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
492 $contacts = DBA::select('contact', ['url'], $condition);
493 while ($contact = DBA::fetch($contacts)) {
494 if (Network::isUrlBlocked($contact['url'])) {
498 $profile = APContact::getByURL($contact['url'], false);
499 if (!empty($profile)) {
500 if (empty($profile['sharedinbox']) || $personal) {
501 $target = $profile['inbox'];
503 $target = $profile['sharedinbox'];
505 $inboxes[$target] = $target;
508 DBA::close($contacts);
514 * Fetches an array of inboxes for the given item and user
517 * @param integer $uid User ID
518 * @param boolean $personal fetch personal inboxes
519 * @param integer $last_id Last item id for adding receivers
521 * @return array with inboxes
522 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
523 * @throws \ImagickException
525 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
527 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
528 if (empty($permissions)) {
534 if ($item['gravity'] == GRAVITY_ACTIVITY) {
535 $item_profile = APContact::getByURL($item['author-link'], false);
537 $item_profile = APContact::getByURL($item['owner-link'], false);
540 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
541 if (empty($permissions[$element])) {
545 $blindcopy = in_array($element, ['bto', 'bcc']);
547 foreach ($permissions[$element] as $receiver) {
548 if (Network::isUrlBlocked($receiver)) {
552 if ($receiver == $item_profile['followers']) {
553 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
555 $profile = APContact::getByURL($receiver, false);
556 if (!empty($profile)) {
557 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
558 $target = $profile['inbox'];
560 $target = $profile['sharedinbox'];
562 $inboxes[$target] = $target;
572 * Returns the activity type of a given item
576 * @return string with activity type
577 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
578 * @throws \ImagickException
580 private static function getTypeOfItem($item)
584 // Only check for a reshare, if it is a real reshare and no quoted reshare
585 if (strpos($item['body'], "[share") === 0) {
586 $announce = api_share_as_retweet($item);
587 $reshared = !empty($announce['plink']);
592 } elseif ($item['verb'] == ACTIVITY_POST) {
593 if ($item['created'] == $item['edited']) {
598 } elseif ($item['verb'] == ACTIVITY_LIKE) {
600 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
602 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
604 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
606 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
607 $type = 'TentativeAccept';
608 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
618 * Creates the activity or fetches it from the cache
620 * @param integer $item_id
621 * @param boolean $force Force new cache entry
623 * @return array with the activity
626 public static function createCachedActivityFromItem($item_id, $force = false)
628 $cachekey = 'APDelivery:createActivity:' . $item_id;
631 $data = Cache::get($cachekey);
632 if (!is_null($data)) {
637 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
639 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
644 * Creates an activity array for a given item id
646 * @param integer $item_id
647 * @param boolean $object_mode Is the activity item is used inside another object?
649 * @return array of activity
652 public static function createActivityFromItem($item_id, $object_mode = false)
654 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
656 if (!DBA::isResult($item)) {
661 $owner = User::getOwnerDataById($item['uid']);
662 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
665 // Disguise forum posts as reshares. Will later be converted to a real announce
666 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
667 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
672 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
673 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
674 if (DBA::isResult($conversation)) {
675 $data = json_decode($conversation['source']);
681 $type = self::getTypeOfItem($item);
685 $data = ['@context' => ActivityPub::CONTEXT];
687 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
689 } elseif ($item['deleted']) {
696 $data['id'] = $item['uri'] . '#' . $type;
697 $data['type'] = $type;
698 $data['actor'] = $item['owner-link'];
700 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
702 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
704 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
706 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
707 $data['object'] = self::createNote($item);
708 } elseif ($data['type'] == 'Announce') {
709 $data = self::createAnnounce($item, $data);
710 } elseif ($data['type'] == 'Follow') {
711 $data['object'] = $item['parent-uri'];
712 } elseif ($data['type'] == 'Undo') {
713 $data['object'] = self::createActivityFromItem($item_id, true);
715 $data['diaspora:guid'] = $item['guid'];
716 if (!empty($item['signed_text'])) {
717 $data['diaspora:like'] = $item['signed_text'];
719 $data['object'] = $item['thr-parent'];
722 if (!empty($item['contact-uid'])) {
723 $uid = $item['contact-uid'];
728 $owner = User::getOwnerDataById($uid);
730 if (!$object_mode && !empty($owner)) {
731 return LDSignature::sign($data, $owner);
736 /// @todo Create "conversation" entry
740 * Creates an object array for a given item id
742 * @param integer $item_id
744 * @return array with the object data
745 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
746 * @throws \ImagickException
748 public static function createObjectFromItemID($item_id)
750 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
752 if (!DBA::isResult($item)) {
756 $data = ['@context' => ActivityPub::CONTEXT];
757 $data = array_merge($data, self::createNote($item));
763 * Creates a location entry for a given item array
767 * @return array with location array
769 private static function createLocation($item)
771 $location = ['type' => 'Place'];
773 if (!empty($item['location'])) {
774 $location['name'] = $item['location'];
779 if (empty($item['coord'])) {
780 $coord = Map::getCoordinates($item['location']);
782 $coords = explode(' ', $item['coord']);
783 if (count($coords) == 2) {
784 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
788 if (!empty($coord['lat']) && !empty($coord['lon'])) {
789 $location['latitude'] = $coord['lat'];
790 $location['longitude'] = $coord['lon'];
797 * Returns a tag array for a given item array
801 * @return array of tags
802 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
804 private static function createTagList($item)
808 $terms = Term::tagArrayFromItemId($item['id']);
809 foreach ($terms as $term) {
810 if ($term['type'] == TERM_HASHTAG) {
811 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
812 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
813 } elseif ($term['type'] == TERM_MENTION) {
814 $contact = Contact::getDetailsByURL($term['url']);
815 if (!empty($contact['addr'])) {
816 $mention = '@' . $contact['addr'];
818 $mention = '@' . $term['url'];
821 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
828 * Adds attachment data to the JSON document
830 * @param array $item Data of the item that is to be posted
831 * @param string $type Object type
833 * @return array with attachment data
834 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
836 private static function createAttachmentList($item, $type)
840 $arr = explode('[/attach],', $item['attach']);
842 foreach ($arr as $r) {
844 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
846 $attributes = ['type' => 'Document',
847 'mediaType' => $matches[3],
848 'url' => $matches[1],
851 if (trim($matches[4]) != '') {
852 $attributes['name'] = trim($matches[4]);
855 $attachments[] = $attributes;
860 if ($type != 'Note') {
864 // Simplify image codes
865 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
867 // Grab all pictures and create attachments out of them
868 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
869 foreach ($pictures[1] as $picture) {
870 $imgdata = Image::getInfoFromURL($picture);
872 $attachments[] = ['type' => 'Document',
873 'mediaType' => $imgdata['mime'],
884 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
886 * @param array $match Matching values for the callback
887 * @return string Replaced mention
888 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
890 private static function mentionCallback($match)
892 if (empty($match[1])) {
896 $data = Contact::getDetailsByURL($match[1]);
897 if (empty($data) || empty($data['nick'])) {
901 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
905 * Remove image elements and replaces them with links to the image
907 * @param string $body
909 * @return string with replaced elements
911 private static function removePictures($body)
913 // Simplify image codes
914 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
916 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
917 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
923 * Fetches the "context" value for a givem item array from the "conversation" table
927 * @return string with context url
930 private static function fetchContextURLForItem($item)
932 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
933 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
934 $context_uri = $conversation['conversation-href'];
935 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
936 $context_uri = $conversation['conversation-uri'];
938 $context_uri = $item['parent-uri'] . '#context';
944 * Returns if the post contains sensitive content ("nsfw")
946 * @param integer $item_id
951 private static function isSensitive($item_id)
953 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
954 return DBA::exists('term', $condition);
962 * @return array with the event data
963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
965 public static function createEvent($item)
968 $event['name'] = $item['event-summary'];
969 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
970 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
972 if (!$item['event-nofinish']) {
973 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
976 if (!empty($item['event-location'])) {
977 $item['location'] = $item['event-location'];
978 $event['location'] = self::createLocation($item);
985 * Creates a note/article object array
989 * @return array with the object data
990 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
991 * @throws \ImagickException
993 public static function createNote($item)
995 if ($item['event-type'] == 'event') {
997 } elseif (!empty($item['title'])) {
1003 if ($item['deleted']) {
1004 $type = 'Tombstone';
1008 $data['id'] = $item['uri'];
1009 $data['type'] = $type;
1011 if ($item['deleted']) {
1015 $data['summary'] = null; // Ignore by now
1017 if ($item['uri'] != $item['thr-parent']) {
1018 $data['inReplyTo'] = $item['thr-parent'];
1020 $data['inReplyTo'] = null;
1023 $data['diaspora:guid'] = $item['guid'];
1024 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1026 if ($item['created'] != $item['edited']) {
1027 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1030 $data['url'] = $item['plink'];
1031 $data['attributedTo'] = $item['author-link'];
1032 $data['sensitive'] = self::isSensitive($item['id']);
1033 $data['context'] = self::fetchContextURLForItem($item);
1035 if (!empty($item['title'])) {
1036 $data['name'] = BBCode::toPlaintext($item['title'], false);
1039 $body = $item['body'];
1041 if ($type == 'Note') {
1042 $body = self::removePictures($body);
1045 if ($type == 'Event') {
1046 $data = array_merge($data, self::createEvent($item));
1048 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1049 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1051 $data['content'] = BBCode::convert($body, false, 7);
1054 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1056 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1057 $data['diaspora:comment'] = $item['signed_text'];
1060 $data['attachment'] = self::createAttachmentList($item, $type);
1061 $data['tag'] = self::createTagList($item);
1063 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1064 $data['location'] = self::createLocation($item);
1067 if (!empty($item['app'])) {
1068 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1071 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1077 * Creates an announce object entry
1079 * @param array $item
1080 * @param array $data activity data
1082 * @return array with activity data
1083 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1084 * @throws \ImagickException
1086 private static function createAnnounce($item, $data)
1088 $announce = api_share_as_retweet($item);
1089 if (empty($announce['plink'])) {
1090 $data['type'] = 'Create';
1091 $data['object'] = self::createNote($item);
1095 // Fetch the original id of the object
1096 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1097 if (!empty($activity)) {
1098 $ldactivity = JsonLD::compact($activity);
1099 $id = JsonLD::fetchElement($ldactivity, '@id');
1101 $data['object'] = $id;
1106 $data['type'] = 'Create';
1107 $data['object'] = self::createNote($item);
1112 * Creates an activity id for a given contact id
1114 * @param integer $cid Contact ID of target
1116 * @return bool|string activity id
1118 public static function activityIDFromContact($cid)
1120 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1121 if (!DBA::isResult($contact)) {
1125 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1126 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1127 return System::baseUrl() . '/activity/' . $uuid;
1131 * Transmits a contact suggestion to a given inbox
1133 * @param integer $uid User ID
1134 * @param string $inbox Target inbox
1135 * @param integer $suggestion_id Suggestion ID
1137 * @return boolean was the transmission successful?
1138 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1142 $owner = User::getOwnerDataById($uid);
1144 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1146 $data = ['@context' => ActivityPub::CONTEXT,
1147 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1148 'type' => 'Announce',
1149 'actor' => $owner['url'],
1150 'object' => $suggestion['url'],
1151 'content' => $suggestion['note'],
1152 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1153 'to' => [ActivityPub::PUBLIC_COLLECTION],
1156 $signed = LDSignature::sign($data, $owner);
1158 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1159 return HTTPSignature::transmit($signed, $inbox, $uid);
1163 * Transmits a profile relocation to a given inbox
1165 * @param integer $uid User ID
1166 * @param string $inbox Target inbox
1168 * @return boolean was the transmission successful?
1169 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1171 public static function sendProfileRelocation($uid, $inbox)
1173 $owner = User::getOwnerDataById($uid);
1175 $data = ['@context' => ActivityPub::CONTEXT,
1176 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1177 'type' => 'dfrn:relocate',
1178 'actor' => $owner['url'],
1179 'object' => $owner['url'],
1180 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1181 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1182 'to' => [ActivityPub::PUBLIC_COLLECTION],
1185 $signed = LDSignature::sign($data, $owner);
1187 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1188 return HTTPSignature::transmit($signed, $inbox, $uid);
1192 * Transmits a profile deletion to a given inbox
1194 * @param integer $uid User ID
1195 * @param string $inbox Target inbox
1197 * @return boolean was the transmission successful?
1198 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1200 public static function sendProfileDeletion($uid, $inbox)
1202 $owner = User::getOwnerDataById($uid);
1204 $data = ['@context' => ActivityPub::CONTEXT,
1205 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1207 'actor' => $owner['url'],
1208 'object' => $owner['url'],
1209 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1210 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1211 'to' => [ActivityPub::PUBLIC_COLLECTION],
1214 $signed = LDSignature::sign($data, $owner);
1216 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1217 return HTTPSignature::transmit($signed, $inbox, $uid);
1221 * Transmits a profile change to a given inbox
1223 * @param integer $uid User ID
1224 * @param string $inbox Target inbox
1226 * @return boolean was the transmission successful?
1227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228 * @throws \ImagickException
1230 public static function sendProfileUpdate($uid, $inbox)
1232 $owner = User::getOwnerDataById($uid);
1233 $profile = APContact::getByURL($owner['url']);
1235 $data = ['@context' => ActivityPub::CONTEXT,
1236 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1238 'actor' => $owner['url'],
1239 'object' => self::getProfile($uid),
1240 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1241 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1242 'to' => [$profile['followers']],
1245 $signed = LDSignature::sign($data, $owner);
1247 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1248 return HTTPSignature::transmit($signed, $inbox, $uid);
1252 * Transmits a given activity to a target
1254 * @param string $activity Type name
1255 * @param string $target Target profile
1256 * @param integer $uid User ID
1258 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1259 * @throws \ImagickException
1260 * @throws \Exception
1262 public static function sendActivity($activity, $target, $uid, $id = '')
1264 $profile = APContact::getByURL($target);
1266 $owner = User::getOwnerDataById($uid);
1269 $id = System::baseUrl() . '/activity/' . System::createGUID();
1272 $data = ['@context' => ActivityPub::CONTEXT,
1274 'type' => $activity,
1275 'actor' => $owner['url'],
1276 'object' => $profile['url'],
1277 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1278 'to' => [$profile['url']]];
1280 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1282 $signed = LDSignature::sign($data, $owner);
1283 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1287 * Transmits a "follow object" activity to a target
1288 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1290 * @param string $object Object URL
1291 * @param string $target Target profile
1292 * @param integer $uid User ID
1294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1295 * @throws \ImagickException
1296 * @throws \Exception
1298 public static function sendFollowObject($object, $target, $uid)
1300 $profile = APContact::getByURL($target);
1302 $owner = User::getOwnerDataById($uid);
1304 $data = ['@context' => ActivityPub::CONTEXT,
1305 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1307 'actor' => $owner['url'],
1308 'object' => $object,
1309 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1310 'to' => [$profile['url']]];
1312 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1314 $signed = LDSignature::sign($data, $owner);
1315 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1319 * Transmit a message that the contact request had been accepted
1321 * @param string $target Target profile
1323 * @param integer $uid User ID
1324 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1325 * @throws \ImagickException
1327 public static function sendContactAccept($target, $id, $uid)
1329 $profile = APContact::getByURL($target);
1331 $owner = User::getOwnerDataById($uid);
1332 $data = ['@context' => ActivityPub::CONTEXT,
1333 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1335 'actor' => $owner['url'],
1336 'object' => ['id' => $id, 'type' => 'Follow',
1337 'actor' => $profile['url'],
1338 'object' => $owner['url']],
1339 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1340 'to' => [$profile['url']]];
1342 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1344 $signed = LDSignature::sign($data, $owner);
1345 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1349 * Reject a contact request or terminates the contact relation
1351 * @param string $target Target profile
1353 * @param integer $uid User ID
1354 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1355 * @throws \ImagickException
1357 public static function sendContactReject($target, $id, $uid)
1359 $profile = APContact::getByURL($target);
1361 $owner = User::getOwnerDataById($uid);
1362 $data = ['@context' => ActivityPub::CONTEXT,
1363 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1365 'actor' => $owner['url'],
1366 'object' => ['id' => $id, 'type' => 'Follow',
1367 'actor' => $profile['url'],
1368 'object' => $owner['url']],
1369 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1370 'to' => [$profile['url']]];
1372 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1374 $signed = LDSignature::sign($data, $owner);
1375 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1379 * Transmits a message that we don't want to follow this contact anymore
1381 * @param string $target Target profile
1382 * @param integer $uid User ID
1383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1384 * @throws \ImagickException
1385 * @throws \Exception
1387 public static function sendContactUndo($target, $cid, $uid)
1389 $profile = APContact::getByURL($target);
1391 $object_id = self::activityIDFromContact($cid);
1392 if (empty($object_id)) {
1396 $id = System::baseUrl() . '/activity/' . System::createGUID();
1398 $owner = User::getOwnerDataById($uid);
1399 $data = ['@context' => ActivityPub::CONTEXT,
1402 'actor' => $owner['url'],
1403 'object' => ['id' => $object_id, 'type' => 'Follow',
1404 'actor' => $owner['url'],
1405 'object' => $profile['url']],
1406 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1407 'to' => [$profile['url']]];
1409 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1411 $signed = LDSignature::sign($data, $owner);
1412 HTTPSignature::transmit($signed, $profile['inbox'], $uid);