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 // 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 if ($item['gravity'] == GRAVITY_PARENT) {
337 $actor_profile = APContact::getByURL($item['owner-link']);
339 $actor_profile = APContact::getByURL($item['author-link']);
342 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
344 if (!$item['private']) {
345 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
347 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
349 foreach ($terms as $term) {
350 $profile = APContact::getByURL($term['url'], false);
351 if (!empty($profile)) {
352 $data['to'][] = $profile['url'];
356 $receiver_list = Item::enumeratePermissions($item);
358 foreach ($terms as $term) {
359 $cid = Contact::getIdForURL($term['url'], $item['uid']);
360 if (!empty($cid) && in_array($cid, $receiver_list)) {
361 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
362 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
363 $data['to'][] = $profile['url'];
368 foreach ($receiver_list as $receiver) {
369 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
370 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
371 if ($contact['hidden'] || $always_bcc) {
372 $data['bcc'][] = $profile['url'];
374 $data['cc'][] = $profile['url'];
380 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
381 while ($parent = Item::fetch($parents)) {
382 if ($parent['gravity'] == GRAVITY_PARENT) {
383 $profile = APContact::getByURL($parent['owner-link'], false);
384 if (!empty($profile)) {
385 if ($item['gravity'] != GRAVITY_PARENT) {
386 // Comments to forums are directed to the forum
387 // But comments to forums aren't directed to the followers collection
388 if ($profile['type'] == 'Group') {
389 $data['to'][] = $profile['url'];
391 $data['cc'][] = $profile['url'];
392 if (!$item['private']) {
393 $data['cc'][] = $actor_profile['followers'];
397 // Public thread parent post always are directed to the followes
398 if (!$item['private']) {
399 $data['cc'][] = $actor_profile['followers'];
405 // Don't include data from future posts
406 if ($parent['id'] >= $last_id) {
410 $profile = APContact::getByURL($parent['author-link'], false);
411 if (!empty($profile)) {
412 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
413 $data['to'][] = $profile['url'];
415 $data['cc'][] = $profile['url'];
419 DBA::close($parents);
421 $data['to'] = array_unique($data['to']);
422 $data['cc'] = array_unique($data['cc']);
423 $data['bcc'] = array_unique($data['bcc']);
425 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
426 unset($data['to'][$key]);
429 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
430 unset($data['cc'][$key]);
433 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
434 unset($data['bcc'][$key]);
437 foreach ($data['to'] as $to) {
438 if (($key = array_search($to, $data['cc'])) !== false) {
439 unset($data['cc'][$key]);
442 if (($key = array_search($to, $data['bcc'])) !== false) {
443 unset($data['bcc'][$key]);
447 foreach ($data['cc'] as $cc) {
448 if (($key = array_search($cc, $data['bcc'])) !== false) {
449 unset($data['bcc'][$key]);
453 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
456 unset($receivers['bcc']);
463 * Fetches a list of inboxes of followers of a given user
465 * @param integer $uid User ID
466 * @param boolean $personal fetch personal inboxes
468 * @return array of follower inboxes
469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
470 * @throws \ImagickException
472 public static function fetchTargetInboxesforUser($uid, $personal = false)
476 // Will be activated in a later step
477 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
479 // For now only send to these contacts:
480 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
482 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
485 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
488 $contacts = DBA::select('contact', ['url'], $condition);
489 while ($contact = DBA::fetch($contacts)) {
490 if (Network::isUrlBlocked($contact['url'])) {
494 $profile = APContact::getByURL($contact['url'], false);
495 if (!empty($profile)) {
496 if (empty($profile['sharedinbox']) || $personal) {
497 $target = $profile['inbox'];
499 $target = $profile['sharedinbox'];
501 $inboxes[$target] = $target;
504 DBA::close($contacts);
510 * Fetches an array of inboxes for the given item and user
513 * @param integer $uid User ID
514 * @param boolean $personal fetch personal inboxes
515 * @param integer $last_id Last item id for adding receivers
517 * @return array with inboxes
518 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
519 * @throws \ImagickException
521 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
523 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
524 if (empty($permissions)) {
530 if ($item['gravity'] == GRAVITY_ACTIVITY) {
531 $item_profile = APContact::getByURL($item['author-link'], false);
533 $item_profile = APContact::getByURL($item['owner-link'], false);
536 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
537 if (empty($permissions[$element])) {
541 $blindcopy = in_array($element, ['bto', 'bcc']);
543 foreach ($permissions[$element] as $receiver) {
544 if (Network::isUrlBlocked($receiver)) {
548 if ($receiver == $item_profile['followers']) {
549 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
551 $profile = APContact::getByURL($receiver, false);
552 if (!empty($profile)) {
553 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
554 $target = $profile['inbox'];
556 $target = $profile['sharedinbox'];
558 $inboxes[$target] = $target;
568 * Returns the activity type of a given item
572 * @return string with activity type
573 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
574 * @throws \ImagickException
576 private static function getTypeOfItem($item)
580 // Only check for a reshare, if it is a real reshare and no quoted reshare
581 if (strpos($item['body'], "[share") === 0) {
582 $announce = api_share_as_retweet($item);
583 $reshared = !empty($announce['plink']);
588 } elseif ($item['verb'] == ACTIVITY_POST) {
589 if ($item['created'] == $item['edited']) {
594 } elseif ($item['verb'] == ACTIVITY_LIKE) {
596 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
598 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
600 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
602 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
603 $type = 'TentativeAccept';
612 * Creates the activity or fetches it from the cache
614 * @param integer $item_id
615 * @param boolean $force Force new cache entry
617 * @return array with the activity
620 public static function createCachedActivityFromItem($item_id, $force = false)
622 $cachekey = 'APDelivery:createActivity:' . $item_id;
625 $data = Cache::get($cachekey);
626 if (!is_null($data)) {
631 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
633 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
638 * Creates an activity array for a given item id
640 * @param integer $item_id
641 * @param boolean $object_mode Is the activity item is used inside another object?
643 * @return array of activity
646 public static function createActivityFromItem($item_id, $object_mode = false)
648 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
650 if (!DBA::isResult($item)) {
655 $owner = User::getOwnerDataById($item['uid']);
656 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
659 // Disguise forum posts as reshares. Will later be converted to a real announce
660 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
661 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
666 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
667 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
668 if (DBA::isResult($conversation)) {
669 $data = json_decode($conversation['source']);
675 $type = self::getTypeOfItem($item);
679 $data = ['@context' => ActivityPub::CONTEXT];
681 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
683 } elseif ($item['deleted']) {
690 $data['id'] = $item['uri'] . '#' . $type;
691 $data['type'] = $type;
692 $data['actor'] = $item['owner-link'];
694 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
696 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
698 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
700 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
701 $data['object'] = self::createNote($item);
702 } elseif ($data['type'] == 'Announce') {
703 $data = self::createAnnounce($item, $data);
704 } elseif ($data['type'] == 'Undo') {
705 $data['object'] = self::createActivityFromItem($item_id, true);
707 $data['diaspora:guid'] = $item['guid'];
708 if (!empty($item['signed_text'])) {
709 $data['diaspora:like'] = $item['signed_text'];
711 $data['object'] = $item['thr-parent'];
714 if (!empty($item['contact-uid'])) {
715 $uid = $item['contact-uid'];
720 $owner = User::getOwnerDataById($uid);
722 if (!$object_mode && !empty($owner)) {
723 return LDSignature::sign($data, $owner);
728 /// @todo Create "conversation" entry
732 * Creates an object array for a given item id
734 * @param integer $item_id
736 * @return array with the object data
737 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
738 * @throws \ImagickException
740 public static function createObjectFromItemID($item_id)
742 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
744 if (!DBA::isResult($item)) {
748 $data = ['@context' => ActivityPub::CONTEXT];
749 $data = array_merge($data, self::createNote($item));
755 * Creates a location entry for a given item array
759 * @return array with location array
761 private static function createLocation($item)
763 $location = ['type' => 'Place'];
765 if (!empty($item['location'])) {
766 $location['name'] = $item['location'];
771 if (empty($item['coord'])) {
772 $coord = Map::getCoordinates($item['location']);
774 $coords = explode(' ', $item['coord']);
775 if (count($coords) == 2) {
776 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
780 if (!empty($coord['lat']) && !empty($coord['lon'])) {
781 $location['latitude'] = $coord['lat'];
782 $location['longitude'] = $coord['lon'];
789 * Returns a tag array for a given item array
793 * @return array of tags
794 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
796 private static function createTagList($item)
800 $terms = Term::tagArrayFromItemId($item['id']);
801 foreach ($terms as $term) {
802 if ($term['type'] == TERM_HASHTAG) {
803 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
804 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
805 } elseif ($term['type'] == TERM_MENTION) {
806 $contact = Contact::getDetailsByURL($term['url']);
807 if (!empty($contact['addr'])) {
808 $mention = '@' . $contact['addr'];
810 $mention = '@' . $term['url'];
813 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
820 * Adds attachment data to the JSON document
822 * @param array $item Data of the item that is to be posted
823 * @param string $type Object type
825 * @return array with attachment data
826 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
828 private static function createAttachmentList($item, $type)
832 $arr = explode('[/attach],', $item['attach']);
834 foreach ($arr as $r) {
836 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
838 $attributes = ['type' => 'Document',
839 'mediaType' => $matches[3],
840 'url' => $matches[1],
843 if (trim($matches[4]) != '') {
844 $attributes['name'] = trim($matches[4]);
847 $attachments[] = $attributes;
852 if ($type != 'Note') {
856 // Simplify image codes
857 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
859 // Grab all pictures and create attachments out of them
860 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
861 foreach ($pictures[1] as $picture) {
862 $imgdata = Image::getInfoFromURL($picture);
864 $attachments[] = ['type' => 'Document',
865 'mediaType' => $imgdata['mime'],
876 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
878 * @param array $match Matching values for the callback
879 * @return string Replaced mention
880 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
882 private static function mentionCallback($match)
884 if (empty($match[1])) {
888 $data = Contact::getDetailsByURL($match[1]);
889 if (empty($data) || empty($data['nick'])) {
893 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
897 * Remove image elements and replaces them with links to the image
899 * @param string $body
901 * @return string with replaced elements
903 private static function removePictures($body)
905 // Simplify image codes
906 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
908 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
909 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
915 * Fetches the "context" value for a givem item array from the "conversation" table
919 * @return string with context url
922 private static function fetchContextURLForItem($item)
924 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
925 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
926 $context_uri = $conversation['conversation-href'];
927 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
928 $context_uri = $conversation['conversation-uri'];
930 $context_uri = $item['parent-uri'] . '#context';
936 * Returns if the post contains sensitive content ("nsfw")
938 * @param integer $item_id
943 private static function isSensitive($item_id)
945 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
946 return DBA::exists('term', $condition);
954 * @return array with the event data
955 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
957 public static function createEvent($item)
960 $event['name'] = $item['event-summary'];
961 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
962 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
964 if (!$item['event-nofinish']) {
965 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
968 if (!empty($item['event-location'])) {
969 $item['location'] = $item['event-location'];
970 $event['location'] = self::createLocation($item);
977 * Creates a note/article object array
981 * @return array with the object data
982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
983 * @throws \ImagickException
985 public static function createNote($item)
987 if ($item['event-type'] == 'event') {
989 } elseif (!empty($item['title'])) {
995 if ($item['deleted']) {
1000 $data['id'] = $item['uri'];
1001 $data['type'] = $type;
1003 if ($item['deleted']) {
1007 $data['summary'] = null; // Ignore by now
1009 if ($item['uri'] != $item['thr-parent']) {
1010 $data['inReplyTo'] = $item['thr-parent'];
1012 $data['inReplyTo'] = null;
1015 $data['diaspora:guid'] = $item['guid'];
1016 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1018 if ($item['created'] != $item['edited']) {
1019 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1022 $data['url'] = $item['plink'];
1023 $data['attributedTo'] = $item['author-link'];
1024 $data['sensitive'] = self::isSensitive($item['id']);
1025 $data['context'] = self::fetchContextURLForItem($item);
1027 if (!empty($item['title'])) {
1028 $data['name'] = BBCode::toPlaintext($item['title'], false);
1031 $body = $item['body'];
1033 if ($type == 'Note') {
1034 $body = self::removePictures($body);
1037 if ($type == 'Event') {
1038 $data = array_merge($data, self::createEvent($item));
1040 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1041 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1043 $data['content'] = BBCode::convert($body, false, 7);
1046 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1048 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1049 $data['diaspora:comment'] = $item['signed_text'];
1052 $data['attachment'] = self::createAttachmentList($item, $type);
1053 $data['tag'] = self::createTagList($item);
1055 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1056 $data['location'] = self::createLocation($item);
1059 if (!empty($item['app'])) {
1060 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1063 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1069 * Creates an announce object entry
1071 * @param array $item
1072 * @param array $data activity data
1074 * @return array with activity data
1075 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1076 * @throws \ImagickException
1078 private static function createAnnounce($item, $data)
1080 $announce = api_share_as_retweet($item);
1081 if (empty($announce['plink'])) {
1082 $data['type'] = 'Create';
1083 $data['object'] = self::createNote($item);
1087 // Fetch the original id of the object
1088 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1089 if (!empty($activity)) {
1090 $ldactivity = JsonLD::compact($activity);
1091 $id = JsonLD::fetchElement($ldactivity, '@id');
1093 $data['object'] = $id;
1098 $data['type'] = 'Create';
1099 $data['object'] = self::createNote($item);
1104 * Creates an activity id for a given contact id
1106 * @param integer $cid Contact ID of target
1108 * @return bool|string activity id
1110 public static function activityIDFromContact($cid)
1112 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1113 if (!DBA::isResult($contact)) {
1117 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1118 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1119 return System::baseUrl() . '/activity/' . $uuid;
1123 * Transmits a contact suggestion to a given inbox
1125 * @param integer $uid User ID
1126 * @param string $inbox Target inbox
1127 * @param integer $suggestion_id Suggestion ID
1129 * @return boolean was the transmission successful?
1130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1132 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1134 $owner = User::getOwnerDataById($uid);
1136 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1138 $data = ['@context' => ActivityPub::CONTEXT,
1139 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1140 'type' => 'Announce',
1141 'actor' => $owner['url'],
1142 'object' => $suggestion['url'],
1143 'content' => $suggestion['note'],
1144 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1145 'to' => [ActivityPub::PUBLIC_COLLECTION],
1148 $signed = LDSignature::sign($data, $owner);
1150 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1151 return HTTPSignature::transmit($signed, $inbox, $uid);
1155 * Transmits a profile relocation to a given inbox
1157 * @param integer $uid User ID
1158 * @param string $inbox Target inbox
1160 * @return boolean was the transmission successful?
1161 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1163 public static function sendProfileRelocation($uid, $inbox)
1165 $owner = User::getOwnerDataById($uid);
1167 $data = ['@context' => ActivityPub::CONTEXT,
1168 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1169 'type' => 'dfrn:relocate',
1170 'actor' => $owner['url'],
1171 'object' => $owner['url'],
1172 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1173 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1174 'to' => [ActivityPub::PUBLIC_COLLECTION],
1177 $signed = LDSignature::sign($data, $owner);
1179 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1180 return HTTPSignature::transmit($signed, $inbox, $uid);
1184 * Transmits a profile deletion to a given inbox
1186 * @param integer $uid User ID
1187 * @param string $inbox Target inbox
1189 * @return boolean was the transmission successful?
1190 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1192 public static function sendProfileDeletion($uid, $inbox)
1194 $owner = User::getOwnerDataById($uid);
1196 $data = ['@context' => ActivityPub::CONTEXT,
1197 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1199 'actor' => $owner['url'],
1200 'object' => $owner['url'],
1201 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1202 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1203 'to' => [ActivityPub::PUBLIC_COLLECTION],
1206 $signed = LDSignature::sign($data, $owner);
1208 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1209 return HTTPSignature::transmit($signed, $inbox, $uid);
1213 * Transmits a profile change to a given inbox
1215 * @param integer $uid User ID
1216 * @param string $inbox Target inbox
1218 * @return boolean was the transmission successful?
1219 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1220 * @throws \ImagickException
1222 public static function sendProfileUpdate($uid, $inbox)
1224 $owner = User::getOwnerDataById($uid);
1225 $profile = APContact::getByURL($owner['url']);
1227 $data = ['@context' => ActivityPub::CONTEXT,
1228 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1230 'actor' => $owner['url'],
1231 'object' => self::getProfile($uid),
1232 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1233 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1234 'to' => [$profile['followers']],
1237 $signed = LDSignature::sign($data, $owner);
1239 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1240 return HTTPSignature::transmit($signed, $inbox, $uid);
1244 * Transmits a given activity to a target
1246 * @param string $activity Type name
1247 * @param string $target Target profile
1248 * @param integer $uid User ID
1250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1251 * @throws \ImagickException
1252 * @throws \Exception
1254 public static function sendActivity($activity, $target, $uid, $id = '')
1256 $profile = APContact::getByURL($target);
1258 $owner = User::getOwnerDataById($uid);
1261 $id = System::baseUrl() . '/activity/' . System::createGUID();
1264 $data = ['@context' => ActivityPub::CONTEXT,
1266 'type' => $activity,
1267 'actor' => $owner['url'],
1268 'object' => $profile['url'],
1269 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1270 'to' => [$profile['url']]];
1272 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1274 $signed = LDSignature::sign($data, $owner);
1275 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1279 * Transmit a message that the contact request had been accepted
1281 * @param string $target Target profile
1283 * @param integer $uid User ID
1284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1285 * @throws \ImagickException
1287 public static function sendContactAccept($target, $id, $uid)
1289 $profile = APContact::getByURL($target);
1291 $owner = User::getOwnerDataById($uid);
1292 $data = ['@context' => ActivityPub::CONTEXT,
1293 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1295 'actor' => $owner['url'],
1296 'object' => ['id' => $id, 'type' => 'Follow',
1297 'actor' => $profile['url'],
1298 'object' => $owner['url']],
1299 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1300 'to' => [$profile['url']]];
1302 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1304 $signed = LDSignature::sign($data, $owner);
1305 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1309 * Reject a contact request or terminates the contact relation
1311 * @param string $target Target profile
1313 * @param integer $uid User ID
1314 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1315 * @throws \ImagickException
1317 public static function sendContactReject($target, $id, $uid)
1319 $profile = APContact::getByURL($target);
1321 $owner = User::getOwnerDataById($uid);
1322 $data = ['@context' => ActivityPub::CONTEXT,
1323 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1325 'actor' => $owner['url'],
1326 'object' => ['id' => $id, 'type' => 'Follow',
1327 'actor' => $profile['url'],
1328 'object' => $owner['url']],
1329 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1330 'to' => [$profile['url']]];
1332 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1334 $signed = LDSignature::sign($data, $owner);
1335 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1339 * Transmits a message that we don't want to follow this contact anymore
1341 * @param string $target Target profile
1342 * @param integer $uid User ID
1343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1344 * @throws \ImagickException
1345 * @throws \Exception
1347 public static function sendContactUndo($target, $cid, $uid)
1349 $profile = APContact::getByURL($target);
1351 $object_id = self::activityIDFromContact($cid);
1352 if (empty($object_id)) {
1356 $id = System::baseUrl() . '/activity/' . System::createGUID();
1358 $owner = User::getOwnerDataById($uid);
1359 $data = ['@context' => ActivityPub::CONTEXT,
1362 'actor' => $owner['url'],
1363 'object' => ['id' => $object_id, 'type' => 'Follow',
1364 'actor' => $owner['url'],
1365 'object' => $profile['url']],
1366 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1367 'to' => [$profile['url']]];
1369 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1371 $signed = LDSignature::sign($data, $owner);
1372 HTTPSignature::transmit($signed, $profile['inbox'], $uid);