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';
33 * @brief ActivityPub Transmitter Protocol class
41 * collects the lost of followers of the given owner
43 * @param array $owner Owner array
44 * @param integer $page Page number
46 * @return array of owners
47 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
49 public static function getFollowers($owner, $page = null)
51 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
52 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
53 $count = DBA::count('contact', $condition);
55 $data = ['@context' => ActivityPub::CONTEXT];
56 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
57 $data['type'] = 'OrderedCollection';
58 $data['totalItems'] = $count;
60 // When we hide our friends we will only show the pure number but don't allow more.
61 $profile = Profile::getByUID($owner['uid']);
62 if (!empty($profile['hide-friends'])) {
67 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
71 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
72 while ($contact = DBA::fetch($contacts)) {
73 $list[] = $contact['url'];
77 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
80 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
82 $data['orderedItems'] = $list;
89 * Create list of following contacts
91 * @param array $owner Owner array
92 * @param integer $page Page numbe
94 * @return array of following contacts
95 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
97 public static function getFollowing($owner, $page = null)
99 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
100 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
101 $count = DBA::count('contact', $condition);
103 $data = ['@context' => ActivityPub::CONTEXT];
104 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
105 $data['type'] = 'OrderedCollection';
106 $data['totalItems'] = $count;
108 // When we hide our friends we will only show the pure number but don't allow more.
109 $profile = Profile::getByUID($owner['uid']);
110 if (!empty($profile['hide-friends'])) {
115 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
119 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
120 while ($contact = DBA::fetch($contacts)) {
121 $list[] = $contact['url'];
125 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
128 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
130 $data['orderedItems'] = $list;
137 * Public posts for the given owner
139 * @param array $owner Owner array
140 * @param integer $page Page numbe
142 * @return array of posts
143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
144 * @throws \ImagickException
146 public static function getOutbox($owner, $page = null)
148 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
150 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
151 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
152 'deleted' => false, 'visible' => true];
153 $count = DBA::count('item', $condition);
155 $data = ['@context' => ActivityPub::CONTEXT];
156 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
157 $data['type'] = 'OrderedCollection';
158 $data['totalItems'] = $count;
161 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
165 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
167 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
168 while ($item = Item::fetch($items)) {
169 $object = self::createObjectFromItemID($item['id']);
170 unset($object['@context']);
175 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
178 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
180 $data['orderedItems'] = $list;
187 * Return the ActivityPub profile of the given user
189 * @param integer $uid User ID
190 * @return array with profile data
191 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193 public static function getProfile($uid)
195 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
196 'account_removed' => false, 'verified' => true];
197 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
198 $user = DBA::selectFirst('user', $fields, $condition);
199 if (!DBA::isResult($user)) {
203 $fields = ['locality', 'region', 'country-name'];
204 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
205 if (!DBA::isResult($profile)) {
209 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
210 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
211 if (!DBA::isResult($contact)) {
215 // On old installations and never changed contacts this might not be filled
216 if (empty($contact['avatar'])) {
217 $contact['avatar'] = $contact['photo'];
220 $data = ['@context' => ActivityPub::CONTEXT];
221 $data['id'] = $contact['url'];
222 $data['diaspora:guid'] = $user['guid'];
223 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
224 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
225 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
226 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
227 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
228 $data['preferredUsername'] = $user['nickname'];
229 $data['name'] = $contact['name'];
230 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
231 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
232 $data['summary'] = $contact['about'];
233 $data['url'] = $contact['url'];
234 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
235 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
236 'owner' => $contact['url'],
237 'publicKeyPem' => $user['pubkey']];
238 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
239 $data['icon'] = ['type' => 'Image',
240 'url' => $contact['avatar']];
242 // tags: https://kitty.town/@inmysocks/100656097926961126.json
247 * Returns an array with permissions of a given item array
251 * @return array with permissions
252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253 * @throws \ImagickException
255 private static function fetchPermissionBlockFromConversation($item)
257 if (empty($item['thr-parent'])) {
261 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
262 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
263 if (!DBA::isResult($conversation)) {
267 $activity = json_decode($conversation['source'], true);
269 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
270 $profile = APContact::getByURL($actor);
272 $item_profile = APContact::getByURL($item['author-link']);
273 $exclude[] = $item['author-link'];
275 if ($item['gravity'] == GRAVITY_PARENT) {
276 $exclude[] = $item['owner-link'];
279 $permissions['to'][] = $actor;
281 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
282 if (empty($activity[$element])) {
285 if (is_string($activity[$element])) {
286 $activity[$element] = [$activity[$element]];
289 foreach ($activity[$element] as $receiver) {
290 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
291 $permissions[$element][] = $item_profile['followers'];
292 } elseif (!in_array($receiver, $exclude)) {
293 $permissions[$element][] = $receiver;
301 * Creates an array of permissions from an item thread
304 * @param boolean $blindcopy
305 * @param boolean $last_id
307 * @return array with permission data
308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309 * @throws \ImagickException
311 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
314 $last_id = $item['id'];
319 // Check if we should always deliver our stuff via BCC
320 if (!empty($item['uid'])) {
321 $profile = Profile::getByUID($item['uid']);
322 if (!empty($profile)) {
323 $always_bcc = $profile['hide-friends'];
327 // Will be activated in a later step
328 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
330 // For now only send to these contacts:
331 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
333 $data = ['to' => [], 'cc' => [], 'bcc' => []];
335 $actor_profile = APContact::getByURL($item['author-link']);
337 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
339 if (!$item['private']) {
340 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
342 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
343 if (!empty($actor_profile['followers'])) {
344 $data['cc'][] = $actor_profile['followers'];
347 foreach ($terms as $term) {
348 $profile = APContact::getByURL($term['url'], false);
349 if (!empty($profile)) {
350 $data['to'][] = $profile['url'];
354 $receiver_list = Item::enumeratePermissions($item);
356 foreach ($terms as $term) {
357 $cid = Contact::getIdForURL($term['url'], $item['uid']);
358 if (!empty($cid) && in_array($cid, $receiver_list)) {
359 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
360 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
361 $data['to'][] = $profile['url'];
366 foreach ($receiver_list as $receiver) {
367 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
368 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
369 if ($contact['hidden'] || $always_bcc) {
370 $data['bcc'][] = $profile['url'];
372 $data['cc'][] = $profile['url'];
378 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
379 while ($parent = Item::fetch($parents)) {
380 // Don't include data from future posts
381 if ($parent['id'] >= $last_id) {
385 $profile = APContact::getByURL($parent['author-link'], false);
386 if (!empty($profile)) {
387 if ($parent['uri'] == $item['thr-parent']) {
388 $data['to'][] = $profile['url'];
390 $data['cc'][] = $profile['url'];
394 if ($item['gravity'] != GRAVITY_PARENT) {
398 $profile = APContact::getByURL($parent['owner-link'], false);
399 if (!empty($profile)) {
400 $data['cc'][] = $profile['url'];
403 DBA::close($parents);
405 $data['to'] = array_unique($data['to']);
406 $data['cc'] = array_unique($data['cc']);
407 $data['bcc'] = array_unique($data['bcc']);
409 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
410 unset($data['to'][$key]);
413 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
414 unset($data['cc'][$key]);
417 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
418 unset($data['bcc'][$key]);
421 foreach ($data['to'] as $to) {
422 if (($key = array_search($to, $data['cc'])) !== false) {
423 unset($data['cc'][$key]);
426 if (($key = array_search($to, $data['bcc'])) !== false) {
427 unset($data['bcc'][$key]);
431 foreach ($data['cc'] as $cc) {
432 if (($key = array_search($cc, $data['bcc'])) !== false) {
433 unset($data['bcc'][$key]);
437 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
440 unset($receivers['bcc']);
447 * Fetches a list of inboxes of followers of a given user
449 * @param integer $uid User ID
450 * @param boolean $personal fetch personal inboxes
452 * @return array of follower inboxes
453 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
454 * @throws \ImagickException
456 public static function fetchTargetInboxesforUser($uid, $personal = false)
460 // Will be activated in a later step
461 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
463 // For now only send to these contacts:
464 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
466 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
469 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
472 $contacts = DBA::select('contact', ['url'], $condition);
473 while ($contact = DBA::fetch($contacts)) {
474 if (Network::isUrlBlocked($contact['url'])) {
478 $profile = APContact::getByURL($contact['url'], false);
479 if (!empty($profile)) {
480 if (empty($profile['sharedinbox']) || $personal) {
481 $target = $profile['inbox'];
483 $target = $profile['sharedinbox'];
485 $inboxes[$target] = $target;
488 DBA::close($contacts);
494 * Fetches an array of inboxes for the given item and user
497 * @param integer $uid User ID
498 * @param boolean $personal fetch personal inboxes
499 * @param integer $last_id Last item id for adding receivers
501 * @return array with inboxes
502 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
503 * @throws \ImagickException
505 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
507 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
508 if (empty($permissions)) {
514 if ($item['gravity'] == GRAVITY_ACTIVITY) {
515 $item_profile = APContact::getByURL($item['author-link'], false);
517 $item_profile = APContact::getByURL($item['owner-link'], false);
520 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
521 if (empty($permissions[$element])) {
525 $blindcopy = in_array($element, ['bto', 'bcc']);
527 foreach ($permissions[$element] as $receiver) {
528 if (Network::isUrlBlocked($receiver)) {
532 if ($receiver == $item_profile['followers']) {
533 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
535 $profile = APContact::getByURL($receiver, false);
536 if (!empty($profile)) {
537 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
538 $target = $profile['inbox'];
540 $target = $profile['sharedinbox'];
542 $inboxes[$target] = $target;
552 * Returns the activity type of a given item
556 * @return string with activity type
557 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
558 * @throws \ImagickException
560 private static function getTypeOfItem($item)
564 // Only check for a reshare, if it is a real reshare and no quoted reshare
565 if (strpos($item['body'], "[share") === 0) {
566 $announce = api_share_as_retweet($item);
567 $reshared = !empty($announce['plink']);
572 } elseif ($item['verb'] == ACTIVITY_POST) {
573 if ($item['created'] == $item['edited']) {
578 } elseif ($item['verb'] == ACTIVITY_LIKE) {
580 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
582 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
584 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
586 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
587 $type = 'TentativeAccept';
596 * Creates the activity or fetches it from the cache
598 * @param integer $item_id
599 * @param boolean $force Force new cache entry
601 * @return array with the activity
604 public static function createCachedActivityFromItem($item_id, $force = false)
606 $cachekey = 'APDelivery:createActivity:' . $item_id;
609 $data = Cache::get($cachekey);
610 if (!is_null($data)) {
615 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
617 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
622 * Creates an activity array for a given item id
624 * @param integer $item_id
625 * @param boolean $object_mode Is the activity item is used inside another object?
627 * @return array of activity
630 public static function createActivityFromItem($item_id, $object_mode = false)
632 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
634 if (!DBA::isResult($item)) {
638 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
639 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
640 if (DBA::isResult($conversation)) {
641 $data = json_decode($conversation['source']);
647 $type = self::getTypeOfItem($item);
650 $data = ['@context' => ActivityPub::CONTEXT];
652 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
654 } elseif ($item['deleted']) {
661 $data['id'] = $item['uri'] . '#' . $type;
662 $data['type'] = $type;
663 $data['actor'] = $item['owner-link'];
665 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
667 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
669 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
671 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
672 $data['object'] = self::createNote($item);
673 } elseif ($data['type'] == 'Announce') {
674 $data['object'] = self::createAnnounce($item);
675 } elseif ($data['type'] == 'Undo') {
676 $data['object'] = self::createActivityFromItem($item_id, true);
678 $data['diaspora:guid'] = $item['guid'];
679 if (!empty($item['signed_text'])) {
680 $data['diaspora:like'] = $item['signed_text'];
682 $data['object'] = $item['thr-parent'];
685 if (!empty($item['contact-uid'])) {
686 $uid = $item['contact-uid'];
691 $owner = User::getOwnerDataById($uid);
693 if (!$object_mode && !empty($owner)) {
694 return LDSignature::sign($data, $owner);
699 /// @todo Create "conversation" entry
703 * Creates an object array for a given item id
705 * @param integer $item_id
707 * @return array with the object data
708 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
709 * @throws \ImagickException
711 public static function createObjectFromItemID($item_id)
713 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
715 if (!DBA::isResult($item)) {
719 $data = ['@context' => ActivityPub::CONTEXT];
720 $data = array_merge($data, self::createNote($item));
726 * Creates a location entry for a given item array
730 * @return array with location array
732 private static function createLocation($item)
734 $location = ['type' => 'Place'];
736 if (!empty($item['location'])) {
737 $location['name'] = $item['location'];
742 if (empty($item['coord'])) {
743 $coord = Map::getCoordinates($item['location']);
745 $coords = explode(' ', $item['coord']);
746 if (count($coords) == 2) {
747 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
751 if (!empty($coord['lat']) && !empty($coord['lon'])) {
752 $location['latitude'] = $coord['lat'];
753 $location['longitude'] = $coord['lon'];
760 * Returns a tag array for a given item array
764 * @return array of tags
765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
767 private static function createTagList($item)
771 $terms = Term::tagArrayFromItemId($item['id']);
772 foreach ($terms as $term) {
773 if ($term['type'] == TERM_HASHTAG) {
774 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
775 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
776 } elseif ($term['type'] == TERM_MENTION) {
777 $contact = Contact::getDetailsByURL($term['url']);
778 if (!empty($contact['addr'])) {
779 $mention = '@' . $contact['addr'];
781 $mention = '@' . $term['url'];
784 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
791 * Adds attachment data to the JSON document
793 * @param array $item Data of the item that is to be posted
794 * @param string $type Object type
796 * @return array with attachment data
797 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
799 private static function createAttachmentList($item, $type)
803 $arr = explode('[/attach],', $item['attach']);
805 foreach ($arr as $r) {
807 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
809 $attributes = ['type' => 'Document',
810 'mediaType' => $matches[3],
811 'url' => $matches[1],
814 if (trim($matches[4]) != '') {
815 $attributes['name'] = trim($matches[4]);
818 $attachments[] = $attributes;
823 if ($type != 'Note') {
827 // Simplify image codes
828 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
830 // Grab all pictures and create attachments out of them
831 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
832 foreach ($pictures[1] as $picture) {
833 $imgdata = Image::getInfoFromURL($picture);
835 $attachments[] = ['type' => 'Document',
836 'mediaType' => $imgdata['mime'],
847 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
849 * @param array $match Matching values for the callback
850 * @return string Replaced mention
851 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
853 private static function mentionCallback($match)
855 if (empty($match[1])) {
859 $data = Contact::getDetailsByURL($match[1]);
860 if (empty($data) || empty($data['nick'])) {
864 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
868 * Remove image elements and replaces them with links to the image
870 * @param string $body
872 * @return string with replaced elements
874 private static function removePictures($body)
876 // Simplify image codes
877 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
879 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
880 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
886 * Fetches the "context" value for a givem item array from the "conversation" table
890 * @return string with context url
893 private static function fetchContextURLForItem($item)
895 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
896 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
897 $context_uri = $conversation['conversation-href'];
898 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
899 $context_uri = $conversation['conversation-uri'];
901 $context_uri = $item['parent-uri'] . '#context';
907 * Returns if the post contains sensitive content ("nsfw")
909 * @param integer $item_id
914 private static function isSensitive($item_id)
916 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
917 return DBA::exists('term', $condition);
925 * @return array with the event data
926 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
928 public static function createEvent($item)
931 $event['name'] = $item['event-summary'];
932 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
933 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
935 if (!$item['event-nofinish']) {
936 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
939 if (!empty($item['event-location'])) {
940 $item['location'] = $item['event-location'];
941 $event['location'] = self::createLocation($item);
948 * Creates a note/article object array
952 * @return array with the object data
953 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954 * @throws \ImagickException
956 public static function createNote($item)
958 if ($item['event-type'] == 'event') {
960 } elseif (!empty($item['title'])) {
966 if ($item['deleted']) {
971 $data['id'] = $item['uri'];
972 $data['type'] = $type;
974 if ($item['deleted']) {
978 $data['summary'] = null; // Ignore by now
980 if ($item['uri'] != $item['thr-parent']) {
981 $data['inReplyTo'] = $item['thr-parent'];
983 $data['inReplyTo'] = null;
986 $data['diaspora:guid'] = $item['guid'];
987 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
989 if ($item['created'] != $item['edited']) {
990 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
993 $data['url'] = $item['plink'];
994 $data['attributedTo'] = $item['author-link'];
995 $data['sensitive'] = self::isSensitive($item['id']);
996 $data['context'] = self::fetchContextURLForItem($item);
998 if (!empty($item['title'])) {
999 $data['name'] = BBCode::toPlaintext($item['title'], false);
1002 $body = $item['body'];
1004 if ($type == 'Note') {
1005 $body = self::removePictures($body);
1008 if ($type == 'Event') {
1009 $data = array_merge($data, self::createEvent($item));
1011 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1012 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1014 $data['content'] = BBCode::convert($body, false, 7);
1017 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1019 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1020 $data['diaspora:comment'] = $item['signed_text'];
1023 $data['attachment'] = self::createAttachmentList($item, $type);
1024 $data['tag'] = self::createTagList($item);
1026 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1027 $data['location'] = self::createLocation($item);
1030 if (!empty($item['app'])) {
1031 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1034 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1040 * Creates an announce object entry
1042 * @param array $item
1044 * @return string with announced object url
1045 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1046 * @throws \ImagickException
1048 public static function createAnnounce($item)
1050 $announce = api_share_as_retweet($item);
1051 if (empty($announce['plink'])) {
1052 return self::createNote($item);
1055 // Fetch the original id of the object
1056 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1057 if (!empty($activity)) {
1058 $ldactivity = JsonLD::compact($activity);
1059 $id = JsonLD::fetchElement($ldactivity, '@id');
1065 return self::createNote($item);
1069 * Creates an activity id for a given contact id
1071 * @param integer $cid Contact ID of target
1073 * @return bool|string activity id
1075 public static function activityIDFromContact($cid)
1077 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1078 if (!DBA::isResult($contact)) {
1082 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1083 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1084 return System::baseUrl() . '/activity/' . $uuid;
1088 * Transmits a contact suggestion to a given inbox
1090 * @param integer $uid User ID
1091 * @param string $inbox Target inbox
1092 * @param integer $suggestion_id Suggestion ID
1094 * @return boolean was the transmission successful?
1095 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1097 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1099 $owner = User::getOwnerDataById($uid);
1101 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1103 $data = ['@context' => ActivityPub::CONTEXT,
1104 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1105 'type' => 'Announce',
1106 'actor' => $owner['url'],
1107 'object' => $suggestion['url'],
1108 'content' => $suggestion['note'],
1109 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1110 'to' => [ActivityPub::PUBLIC_COLLECTION],
1113 $signed = LDSignature::sign($data, $owner);
1115 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1116 return HTTPSignature::transmit($signed, $inbox, $uid);
1120 * Transmits a profile relocation to a given inbox
1122 * @param integer $uid User ID
1123 * @param string $inbox Target inbox
1125 * @return boolean was the transmission successful?
1126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1128 public static function sendProfileRelocation($uid, $inbox)
1130 $owner = User::getOwnerDataById($uid);
1132 $data = ['@context' => ActivityPub::CONTEXT,
1133 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1134 'type' => 'dfrn:relocate',
1135 'actor' => $owner['url'],
1136 'object' => $owner['url'],
1137 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1138 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1139 'to' => [ActivityPub::PUBLIC_COLLECTION],
1142 $signed = LDSignature::sign($data, $owner);
1144 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1145 return HTTPSignature::transmit($signed, $inbox, $uid);
1149 * Transmits a profile deletion to a given inbox
1151 * @param integer $uid User ID
1152 * @param string $inbox Target inbox
1154 * @return boolean was the transmission successful?
1155 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1157 public static function sendProfileDeletion($uid, $inbox)
1159 $owner = User::getOwnerDataById($uid);
1161 $data = ['@context' => ActivityPub::CONTEXT,
1162 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1164 'actor' => $owner['url'],
1165 'object' => $owner['url'],
1166 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1167 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1168 'to' => [ActivityPub::PUBLIC_COLLECTION],
1171 $signed = LDSignature::sign($data, $owner);
1173 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1174 return HTTPSignature::transmit($signed, $inbox, $uid);
1178 * Transmits a profile change to a given inbox
1180 * @param integer $uid User ID
1181 * @param string $inbox Target inbox
1183 * @return boolean was the transmission successful?
1184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1185 * @throws \ImagickException
1187 public static function sendProfileUpdate($uid, $inbox)
1189 $owner = User::getOwnerDataById($uid);
1190 $profile = APContact::getByURL($owner['url']);
1192 $data = ['@context' => ActivityPub::CONTEXT,
1193 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1195 'actor' => $owner['url'],
1196 'object' => self::getProfile($uid),
1197 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1198 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1199 'to' => [$profile['followers']],
1202 $signed = LDSignature::sign($data, $owner);
1204 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1205 return HTTPSignature::transmit($signed, $inbox, $uid);
1209 * Transmits a given activity to a target
1211 * @param string $activity Type name
1212 * @param string $target Target profile
1213 * @param integer $uid User ID
1215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1216 * @throws \ImagickException
1217 * @throws \Exception
1219 public static function sendActivity($activity, $target, $uid, $id = '')
1221 $profile = APContact::getByURL($target);
1223 $owner = User::getOwnerDataById($uid);
1226 $id = System::baseUrl() . '/activity/' . System::createGUID();
1229 $data = ['@context' => ActivityPub::CONTEXT,
1231 'type' => $activity,
1232 'actor' => $owner['url'],
1233 'object' => $profile['url'],
1234 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1235 'to' => [$profile['url']]];
1237 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1239 $signed = LDSignature::sign($data, $owner);
1240 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1244 * Transmit a message that the contact request had been accepted
1246 * @param string $target Target profile
1248 * @param integer $uid User ID
1249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1250 * @throws \ImagickException
1252 public static function sendContactAccept($target, $id, $uid)
1254 $profile = APContact::getByURL($target);
1256 $owner = User::getOwnerDataById($uid);
1257 $data = ['@context' => ActivityPub::CONTEXT,
1258 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1260 'actor' => $owner['url'],
1261 'object' => ['id' => $id, 'type' => 'Follow',
1262 'actor' => $profile['url'],
1263 'object' => $owner['url']],
1264 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1265 'to' => [$profile['url']]];
1267 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1269 $signed = LDSignature::sign($data, $owner);
1270 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1274 * Reject a contact request or terminates the contact relation
1276 * @param string $target Target profile
1278 * @param integer $uid User ID
1279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1280 * @throws \ImagickException
1282 public static function sendContactReject($target, $id, $uid)
1284 $profile = APContact::getByURL($target);
1286 $owner = User::getOwnerDataById($uid);
1287 $data = ['@context' => ActivityPub::CONTEXT,
1288 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1290 'actor' => $owner['url'],
1291 'object' => ['id' => $id, 'type' => 'Follow',
1292 'actor' => $profile['url'],
1293 'object' => $owner['url']],
1294 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1295 'to' => [$profile['url']]];
1297 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1299 $signed = LDSignature::sign($data, $owner);
1300 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1304 * Transmits a message that we don't want to follow this contact anymore
1306 * @param string $target Target profile
1307 * @param integer $uid User ID
1308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1309 * @throws \ImagickException
1310 * @throws \Exception
1312 public static function sendContactUndo($target, $cid, $uid)
1314 $profile = APContact::getByURL($target);
1316 $object_id = self::activityIDFromContact($cid);
1317 if (empty($object_id)) {
1321 $id = System::baseUrl() . '/activity/' . System::createGUID();
1323 $owner = User::getOwnerDataById($uid);
1324 $data = ['@context' => ActivityPub::CONTEXT,
1327 'actor' => $owner['url'],
1328 'object' => ['id' => $object_id, 'type' => 'Follow',
1329 'actor' => $owner['url'],
1330 'object' => $profile['url']],
1331 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1332 'to' => [$profile['url']]];
1334 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1336 $signed = LDSignature::sign($data, $owner);
1337 HTTPSignature::transmit($signed, $profile['inbox'], $uid);