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\Protocol\Diaspora;
27 use Friendica\Core\Cache;
28 use Friendica\Util\Map;
29 use Friendica\Util\Network;
31 require_once 'include/api.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'], [Contact::PAGE_NORMAL, Contact::PAGE_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 // Will be activated in a later step
329 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
331 // For now only send to these contacts:
332 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
334 $data = ['to' => [], 'cc' => [], 'bcc' => []];
336 $actor_profile = APContact::getByURL($item['author-link']);
338 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
340 if (!$item['private']) {
341 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
343 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
344 if (!empty($actor_profile['followers'])) {
345 $data['cc'][] = $actor_profile['followers'];
348 foreach ($terms as $term) {
349 $profile = APContact::getByURL($term['url'], false);
350 if (!empty($profile)) {
351 $data['to'][] = $profile['url'];
355 $receiver_list = Item::enumeratePermissions($item);
359 foreach ($terms as $term) {
360 $cid = Contact::getIdForURL($term['url'], $item['uid']);
361 if (!empty($cid) && in_array($cid, $receiver_list)) {
362 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
363 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
364 $data['to'][] = $profile['url'];
369 foreach ($receiver_list as $receiver) {
370 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
371 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
372 if ($contact['hidden'] || $always_bcc) {
373 $data['bcc'][] = $profile['url'];
375 $data['cc'][] = $profile['url'];
381 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
382 while ($parent = Item::fetch($parents)) {
383 // Don't include data from future posts
384 if ($parent['id'] >= $last_id) {
388 $profile = APContact::getByURL($parent['author-link'], false);
389 if (!empty($profile)) {
390 if ($parent['uri'] == $item['thr-parent']) {
391 $data['to'][] = $profile['url'];
393 $data['cc'][] = $profile['url'];
397 if ($item['gravity'] != GRAVITY_PARENT) {
401 $profile = APContact::getByURL($parent['owner-link'], false);
402 if (!empty($profile)) {
403 $data['cc'][] = $profile['url'];
406 DBA::close($parents);
408 $data['to'] = array_unique($data['to']);
409 $data['cc'] = array_unique($data['cc']);
410 $data['bcc'] = array_unique($data['bcc']);
412 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
413 unset($data['to'][$key]);
416 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
417 unset($data['cc'][$key]);
420 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
421 unset($data['bcc'][$key]);
424 foreach ($data['to'] as $to) {
425 if (($key = array_search($to, $data['cc'])) !== false) {
426 unset($data['cc'][$key]);
429 if (($key = array_search($to, $data['bcc'])) !== false) {
430 unset($data['bcc'][$key]);
434 foreach ($data['cc'] as $cc) {
435 if (($key = array_search($cc, $data['bcc'])) !== false) {
436 unset($data['bcc'][$key]);
440 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
443 unset($receivers['bcc']);
450 * Fetches a list of inboxes of followers of a given user
452 * @param integer $uid User ID
453 * @param boolean $personal fetch personal inboxes
455 * @return array of follower inboxes
456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457 * @throws \ImagickException
459 public static function fetchTargetInboxesforUser($uid, $personal = false)
463 // Will be activated in a later step
464 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
466 // For now only send to these contacts:
467 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
469 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
472 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
475 $contacts = DBA::select('contact', ['url'], $condition);
476 while ($contact = DBA::fetch($contacts)) {
477 if (Network::isUrlBlocked($contact['url'])) {
481 $profile = APContact::getByURL($contact['url'], false);
482 if (!empty($profile)) {
483 if (empty($profile['sharedinbox']) || $personal) {
484 $target = $profile['inbox'];
486 $target = $profile['sharedinbox'];
488 $inboxes[$target] = $target;
491 DBA::close($contacts);
497 * Fetches an array of inboxes for the given item and user
500 * @param integer $uid User ID
501 * @param boolean $personal fetch personal inboxes
502 * @param integer $last_id Last item id for adding receivers
504 * @return array with inboxes
505 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
506 * @throws \ImagickException
508 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
510 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
511 if (empty($permissions)) {
517 if ($item['gravity'] == GRAVITY_ACTIVITY) {
518 $item_profile = APContact::getByURL($item['author-link'], false);
520 $item_profile = APContact::getByURL($item['owner-link'], false);
523 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
524 if (empty($permissions[$element])) {
528 $blindcopy = in_array($element, ['bto', 'bcc']);
530 foreach ($permissions[$element] as $receiver) {
531 if (Network::isUrlBlocked($receiver)) {
535 if ($receiver == $item_profile['followers']) {
536 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
538 $profile = APContact::getByURL($receiver, false);
539 if (!empty($profile)) {
540 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
541 $target = $profile['inbox'];
543 $target = $profile['sharedinbox'];
545 $inboxes[$target] = $target;
555 * Returns the activity type of a given item
559 * @return string with activity type
560 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
561 * @throws \ImagickException
563 private static function getTypeOfItem($item)
567 // Only check for a reshare, if it is a real reshare and no quoted reshare
568 if (strpos($item['body'], "[share") === 0) {
569 $announce = api_share_as_retweet($item);
570 $reshared = !empty($announce['plink']);
575 } elseif ($item['verb'] == ACTIVITY_POST) {
576 if ($item['created'] == $item['edited']) {
581 } elseif ($item['verb'] == ACTIVITY_LIKE) {
583 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
585 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
587 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
589 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
590 $type = 'TentativeAccept';
599 * Creates the activity or fetches it from the cache
601 * @param integer $item_id
602 * @param boolean $force Force new cache entry
604 * @return array with the activity
607 public static function createCachedActivityFromItem($item_id, $force = false)
609 $cachekey = 'APDelivery:createActivity:' . $item_id;
612 $data = Cache::get($cachekey);
613 if (!is_null($data)) {
618 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
620 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
625 * Creates an activity array for a given item id
627 * @param integer $item_id
628 * @param boolean $object_mode Is the activity item is used inside another object?
630 * @return array of activity
633 public static function createActivityFromItem($item_id, $object_mode = false)
635 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
637 if (!DBA::isResult($item)) {
641 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
642 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
643 if (DBA::isResult($conversation)) {
644 $data = json_decode($conversation['source']);
650 $type = self::getTypeOfItem($item);
653 $data = ['@context' => ActivityPub::CONTEXT];
655 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
657 } elseif ($item['deleted']) {
664 $data['id'] = $item['uri'] . '#' . $type;
665 $data['type'] = $type;
666 $data['actor'] = $item['owner-link'];
668 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
670 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
672 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
674 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
675 $data['object'] = self::createNote($item);
676 } elseif ($data['type'] == 'Announce') {
677 $data['object'] = self::createAnnounce($item);
678 } elseif ($data['type'] == 'Undo') {
679 $data['object'] = self::createActivityFromItem($item_id, true);
681 $data['diaspora:guid'] = $item['guid'];
682 if (!empty($item['signed_text'])) {
683 $data['diaspora:like'] = $item['signed_text'];
685 $data['object'] = $item['thr-parent'];
688 if (!empty($item['contact-uid'])) {
689 $uid = $item['contact-uid'];
694 $owner = User::getOwnerDataById($uid);
696 if (!$object_mode && !empty($owner)) {
697 return LDSignature::sign($data, $owner);
702 /// @todo Create "conversation" entry
706 * Creates an object array for a given item id
708 * @param integer $item_id
710 * @return array with the object data
711 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
712 * @throws \ImagickException
714 public static function createObjectFromItemID($item_id)
716 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
718 if (!DBA::isResult($item)) {
722 $data = ['@context' => ActivityPub::CONTEXT];
723 $data = array_merge($data, self::createNote($item));
729 * Creates a location entry for a given item array
733 * @return array with location array
735 private static function createLocation($item)
737 $location = ['type' => 'Place'];
739 if (!empty($item['location'])) {
740 $location['name'] = $item['location'];
745 if (empty($item['coord'])) {
746 $coord = Map::getCoordinates($item['location']);
748 $coords = explode(' ', $item['coord']);
749 if (count($coords) == 2) {
750 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
754 if (!empty($coord['lat']) && !empty($coord['lon'])) {
755 $location['latitude'] = $coord['lat'];
756 $location['longitude'] = $coord['lon'];
763 * Returns a tag array for a given item array
767 * @return array of tags
768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
770 private static function createTagList($item)
774 $terms = Term::tagArrayFromItemId($item['id']);
775 foreach ($terms as $term) {
776 if ($term['type'] == TERM_HASHTAG) {
777 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
778 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
779 } elseif ($term['type'] == TERM_MENTION) {
780 $contact = Contact::getDetailsByURL($term['url']);
781 if (!empty($contact['addr'])) {
782 $mention = '@' . $contact['addr'];
784 $mention = '@' . $term['url'];
787 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
794 * Adds attachment data to the JSON document
796 * @param array $item Data of the item that is to be posted
797 * @param string $type Object type
799 * @return array with attachment data
800 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
802 private static function createAttachmentList($item, $type)
806 $arr = explode('[/attach],', $item['attach']);
808 foreach ($arr as $r) {
810 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
812 $attributes = ['type' => 'Document',
813 'mediaType' => $matches[3],
814 'url' => $matches[1],
817 if (trim($matches[4]) != '') {
818 $attributes['name'] = trim($matches[4]);
821 $attachments[] = $attributes;
826 if ($type != 'Note') {
830 // Simplify image codes
831 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
833 // Grab all pictures and create attachments out of them
834 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
835 foreach ($pictures[1] as $picture) {
836 $imgdata = Image::getInfoFromURL($picture);
838 $attachments[] = ['type' => 'Document',
839 'mediaType' => $imgdata['mime'],
850 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
852 * @param array $match Matching values for the callback
853 * @return string Replaced mention
854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
856 private static function mentionCallback($match)
858 if (empty($match[1])) {
862 $data = Contact::getDetailsByURL($match[1]);
863 if (empty($data) || empty($data['nick'])) {
867 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
871 * Remove image elements and replaces them with links to the image
873 * @param string $body
875 * @return string with replaced elements
877 private static function removePictures($body)
879 // Simplify image codes
880 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
882 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
883 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
889 * Fetches the "context" value for a givem item array from the "conversation" table
893 * @return string with context url
896 private static function fetchContextURLForItem($item)
898 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
899 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
900 $context_uri = $conversation['conversation-href'];
901 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
902 $context_uri = $conversation['conversation-uri'];
904 $context_uri = $item['parent-uri'] . '#context';
910 * Returns if the post contains sensitive content ("nsfw")
912 * @param integer $item_id
917 private static function isSensitive($item_id)
919 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
920 return DBA::exists('term', $condition);
928 * @return array with the event data
929 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
931 public static function createEvent($item)
934 $event['name'] = $item['event-summary'];
935 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
936 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
938 if (!$item['event-nofinish']) {
939 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
942 if (!empty($item['event-location'])) {
943 $item['location'] = $item['event-location'];
944 $event['location'] = self::createLocation($item);
951 * Creates a note/article object array
955 * @return array with the object data
956 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957 * @throws \ImagickException
959 public static function createNote($item)
961 if ($item['event-type'] == 'event') {
963 } elseif (!empty($item['title'])) {
969 if ($item['deleted']) {
974 $data['id'] = $item['uri'];
975 $data['type'] = $type;
977 if ($item['deleted']) {
981 $data['summary'] = null; // Ignore by now
983 if ($item['uri'] != $item['thr-parent']) {
984 $data['inReplyTo'] = $item['thr-parent'];
986 $data['inReplyTo'] = null;
989 $data['diaspora:guid'] = $item['guid'];
990 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
992 if ($item['created'] != $item['edited']) {
993 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
996 $data['url'] = $item['plink'];
997 $data['attributedTo'] = $item['author-link'];
998 $data['sensitive'] = self::isSensitive($item['id']);
999 $data['context'] = self::fetchContextURLForItem($item);
1001 if (!empty($item['title'])) {
1002 $data['name'] = BBCode::toPlaintext($item['title'], false);
1005 $body = $item['body'];
1007 if ($type == 'Note') {
1008 $body = self::removePictures($body);
1011 if ($type == 'Event') {
1012 $data = array_merge($data, self::createEvent($item));
1014 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1015 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1017 $data['content'] = BBCode::convert($body, false, 7);
1020 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1022 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1023 $data['diaspora:comment'] = $item['signed_text'];
1026 $data['attachment'] = self::createAttachmentList($item, $type);
1027 $data['tag'] = self::createTagList($item);
1029 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1030 $data['location'] = self::createLocation($item);
1033 if (!empty($item['app'])) {
1034 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1037 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1043 * Creates an announce object entry
1045 * @param array $item
1047 * @return string with announced object url
1048 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1049 * @throws \ImagickException
1051 public static function createAnnounce($item)
1053 $announce = api_share_as_retweet($item);
1054 if (empty($announce['plink'])) {
1055 return self::createNote($item);
1058 // Fetch the original id of the object
1059 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1060 if (!empty($activity)) {
1061 $ldactivity = JsonLD::compact($activity);
1062 $id = JsonLD::fetchElement($ldactivity, '@id');
1068 return self::createNote($item);
1072 * Creates an activity id for a given contact id
1074 * @param integer $cid Contact ID of target
1076 * @return bool|string activity id
1078 public static function activityIDFromContact($cid)
1080 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1081 if (!DBA::isResult($contact)) {
1085 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1086 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1087 return System::baseUrl() . '/activity/' . $uuid;
1091 * Transmits a contact suggestion to a given inbox
1093 * @param integer $uid User ID
1094 * @param string $inbox Target inbox
1095 * @param integer $suggestion_id Suggestion ID
1097 * @return boolean was the transmission successful?
1098 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1100 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1102 $owner = User::getOwnerDataById($uid);
1104 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1106 $data = ['@context' => ActivityPub::CONTEXT,
1107 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1108 'type' => 'Announce',
1109 'actor' => $owner['url'],
1110 'object' => $suggestion['url'],
1111 'content' => $suggestion['note'],
1112 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1113 'to' => [ActivityPub::PUBLIC_COLLECTION],
1116 $signed = LDSignature::sign($data, $owner);
1118 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1119 return HTTPSignature::transmit($signed, $inbox, $uid);
1123 * Transmits a profile relocation to a given inbox
1125 * @param integer $uid User ID
1126 * @param string $inbox Target inbox
1128 * @return boolean was the transmission successful?
1129 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1131 public static function sendProfileRelocation($uid, $inbox)
1133 $owner = User::getOwnerDataById($uid);
1135 $data = ['@context' => ActivityPub::CONTEXT,
1136 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1137 'type' => 'dfrn:relocate',
1138 'actor' => $owner['url'],
1139 'object' => $owner['url'],
1140 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1141 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1142 'to' => [ActivityPub::PUBLIC_COLLECTION],
1145 $signed = LDSignature::sign($data, $owner);
1147 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1148 return HTTPSignature::transmit($signed, $inbox, $uid);
1152 * Transmits a profile deletion to a given inbox
1154 * @param integer $uid User ID
1155 * @param string $inbox Target inbox
1157 * @return boolean was the transmission successful?
1158 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1160 public static function sendProfileDeletion($uid, $inbox)
1162 $owner = User::getOwnerDataById($uid);
1164 $data = ['@context' => ActivityPub::CONTEXT,
1165 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1167 'actor' => $owner['url'],
1168 'object' => $owner['url'],
1169 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1170 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1171 'to' => [ActivityPub::PUBLIC_COLLECTION],
1174 $signed = LDSignature::sign($data, $owner);
1176 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1177 return HTTPSignature::transmit($signed, $inbox, $uid);
1181 * Transmits a profile change to a given inbox
1183 * @param integer $uid User ID
1184 * @param string $inbox Target inbox
1186 * @return boolean was the transmission successful?
1187 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1188 * @throws \ImagickException
1190 public static function sendProfileUpdate($uid, $inbox)
1192 $owner = User::getOwnerDataById($uid);
1193 $profile = APContact::getByURL($owner['url']);
1195 $data = ['@context' => ActivityPub::CONTEXT,
1196 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1198 'actor' => $owner['url'],
1199 'object' => self::getProfile($uid),
1200 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1201 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1202 'to' => [$profile['followers']],
1205 $signed = LDSignature::sign($data, $owner);
1207 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1208 return HTTPSignature::transmit($signed, $inbox, $uid);
1212 * Transmits a given activity to a target
1214 * @param string $activity Type name
1215 * @param string $target Target profile
1216 * @param integer $uid User ID
1218 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1219 * @throws \ImagickException
1220 * @throws \Exception
1222 public static function sendActivity($activity, $target, $uid, $id = '')
1224 $profile = APContact::getByURL($target);
1226 $owner = User::getOwnerDataById($uid);
1229 $id = System::baseUrl() . '/activity/' . System::createGUID();
1232 $data = ['@context' => ActivityPub::CONTEXT,
1234 'type' => $activity,
1235 'actor' => $owner['url'],
1236 'object' => $profile['url'],
1237 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1238 'to' => [$profile['url']]];
1240 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1242 $signed = LDSignature::sign($data, $owner);
1243 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1247 * Transmit a message that the contact request had been accepted
1249 * @param string $target Target profile
1251 * @param integer $uid User ID
1252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1253 * @throws \ImagickException
1255 public static function sendContactAccept($target, $id, $uid)
1257 $profile = APContact::getByURL($target);
1259 $owner = User::getOwnerDataById($uid);
1260 $data = ['@context' => ActivityPub::CONTEXT,
1261 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1263 'actor' => $owner['url'],
1264 'object' => ['id' => $id, 'type' => 'Follow',
1265 'actor' => $profile['url'],
1266 'object' => $owner['url']],
1267 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1268 'to' => [$profile['url']]];
1270 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1272 $signed = LDSignature::sign($data, $owner);
1273 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1277 * Reject a contact request or terminates the contact relation
1279 * @param string $target Target profile
1281 * @param integer $uid User ID
1282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1283 * @throws \ImagickException
1285 public static function sendContactReject($target, $id, $uid)
1287 $profile = APContact::getByURL($target);
1289 $owner = User::getOwnerDataById($uid);
1290 $data = ['@context' => ActivityPub::CONTEXT,
1291 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1293 'actor' => $owner['url'],
1294 'object' => ['id' => $id, 'type' => 'Follow',
1295 'actor' => $profile['url'],
1296 'object' => $owner['url']],
1297 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1298 'to' => [$profile['url']]];
1300 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1302 $signed = LDSignature::sign($data, $owner);
1303 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1307 * Transmits a message that we don't want to follow this contact anymore
1309 * @param string $target Target profile
1310 * @param integer $uid User ID
1311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1312 * @throws \ImagickException
1313 * @throws \Exception
1315 public static function sendContactUndo($target, $cid, $uid)
1317 $profile = APContact::getByURL($target);
1319 $object_id = self::activityIDFromContact($cid);
1320 if (empty($object_id)) {
1324 $id = System::baseUrl() . '/activity/' . System::createGUID();
1326 $owner = User::getOwnerDataById($uid);
1327 $data = ['@context' => ActivityPub::CONTEXT,
1330 'actor' => $owner['url'],
1331 'object' => ['id' => $object_id, 'type' => 'Follow',
1332 'actor' => $owner['url'],
1333 'object' => $profile['url']],
1334 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1335 'to' => [$profile['url']]];
1337 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1339 $signed = LDSignature::sign($data, $owner);
1340 HTTPSignature::transmit($signed, $profile['inbox'], $uid);