3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\BaseObject;
8 use Friendica\Content\Feature;
9 use Friendica\Database\DBA;
10 use Friendica\Core\Config;
11 use Friendica\Core\Logger;
12 use Friendica\Core\System;
13 use Friendica\Util\HTTPSignature;
14 use Friendica\Core\Protocol;
15 use Friendica\Model\Conversation;
16 use Friendica\Model\Contact;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Item;
19 use Friendica\Model\Term;
20 use Friendica\Model\User;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Util\JsonLD;
24 use Friendica\Util\LDSignature;
25 use Friendica\Model\Profile;
26 use Friendica\Object\Image;
27 use Friendica\Protocol\ActivityPub;
28 use Friendica\Core\Cache;
29 use Friendica\Util\Map;
30 use Friendica\Util\Network;
32 require_once 'include/api.php';
33 require_once 'mod/share.php';
36 * @brief ActivityPub Transmitter Protocol class
44 * collects the lost of followers of the given owner
46 * @param array $owner Owner array
47 * @param integer $page Page number
49 * @return array of owners
50 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
52 public static function getFollowers($owner, $page = null)
54 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
55 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
56 $count = DBA::count('contact', $condition);
58 $data = ['@context' => ActivityPub::CONTEXT];
59 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
60 $data['type'] = 'OrderedCollection';
61 $data['totalItems'] = $count;
63 // When we hide our friends we will only show the pure number but don't allow more.
64 $profile = Profile::getByUID($owner['uid']);
65 if (!empty($profile['hide-friends'])) {
70 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
74 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
75 while ($contact = DBA::fetch($contacts)) {
76 $list[] = $contact['url'];
80 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
83 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
85 $data['orderedItems'] = $list;
92 * Create list of following contacts
94 * @param array $owner Owner array
95 * @param integer $page Page numbe
97 * @return array of following contacts
98 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
100 public static function getFollowing($owner, $page = null)
102 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
103 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
104 $count = DBA::count('contact', $condition);
106 $data = ['@context' => ActivityPub::CONTEXT];
107 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
108 $data['type'] = 'OrderedCollection';
109 $data['totalItems'] = $count;
111 // When we hide our friends we will only show the pure number but don't allow more.
112 $profile = Profile::getByUID($owner['uid']);
113 if (!empty($profile['hide-friends'])) {
118 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
122 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
123 while ($contact = DBA::fetch($contacts)) {
124 $list[] = $contact['url'];
128 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
131 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
133 $data['orderedItems'] = $list;
140 * Public posts for the given owner
142 * @param array $owner Owner array
143 * @param integer $page Page numbe
145 * @return array of posts
146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
147 * @throws \ImagickException
149 public static function getOutbox($owner, $page = null)
151 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
153 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
154 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
155 'deleted' => false, 'visible' => true];
156 $count = DBA::count('item', $condition);
158 $data = ['@context' => ActivityPub::CONTEXT];
159 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
160 $data['type'] = 'OrderedCollection';
161 $data['totalItems'] = $count;
164 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
168 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
170 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
171 while ($item = Item::fetch($items)) {
172 $object = self::createObjectFromItemID($item['id']);
173 unset($object['@context']);
178 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
181 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
183 $data['orderedItems'] = $list;
190 * Return the ActivityPub profile of the given user
192 * @param integer $uid User ID
193 * @return array with profile data
194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196 public static function getProfile($uid)
198 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
199 'account_removed' => false, 'verified' => true];
200 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
201 $user = DBA::selectFirst('user', $fields, $condition);
202 if (!DBA::isResult($user)) {
206 $fields = ['locality', 'region', 'country-name'];
207 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
208 if (!DBA::isResult($profile)) {
212 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
213 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
214 if (!DBA::isResult($contact)) {
218 // On old installations and never changed contacts this might not be filled
219 if (empty($contact['avatar'])) {
220 $contact['avatar'] = $contact['photo'];
223 $data = ['@context' => ActivityPub::CONTEXT];
224 $data['id'] = $contact['url'];
225 $data['diaspora:guid'] = $user['guid'];
226 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
227 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
228 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
229 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
230 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
231 $data['preferredUsername'] = $user['nickname'];
232 $data['name'] = $contact['name'];
233 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
234 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
235 $data['summary'] = $contact['about'];
236 $data['url'] = $contact['url'];
237 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
238 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
239 'owner' => $contact['url'],
240 'publicKeyPem' => $user['pubkey']];
241 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
242 $data['icon'] = ['type' => 'Image',
243 'url' => $contact['avatar']];
245 // tags: https://kitty.town/@inmysocks/100656097926961126.json
250 * Returns an array with permissions of a given item array
254 * @return array with permissions
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 * @throws \ImagickException
258 private static function fetchPermissionBlockFromConversation($item)
260 if (empty($item['thr-parent'])) {
264 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
265 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
266 if (!DBA::isResult($conversation)) {
270 $activity = json_decode($conversation['source'], true);
272 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
273 $profile = APContact::getByURL($actor);
275 $item_profile = APContact::getByURL($item['author-link']);
276 $exclude[] = $item['author-link'];
278 if ($item['gravity'] == GRAVITY_PARENT) {
279 $exclude[] = $item['owner-link'];
282 $permissions['to'][] = $actor;
284 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
285 if (empty($activity[$element])) {
288 if (is_string($activity[$element])) {
289 $activity[$element] = [$activity[$element]];
292 foreach ($activity[$element] as $receiver) {
293 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
294 $permissions[$element][] = $item_profile['followers'];
295 } elseif (!in_array($receiver, $exclude)) {
296 $permissions[$element][] = $receiver;
304 * Creates an array of permissions from an item thread
307 * @param boolean $blindcopy
308 * @param boolean $last_id
310 * @return array with permission data
311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
312 * @throws \ImagickException
314 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
317 $last_id = $item['id'];
322 // Check if we should always deliver our stuff via BCC
323 if (!empty($item['uid'])) {
324 $profile = Profile::getByUID($item['uid']);
325 if (!empty($profile)) {
326 $always_bcc = $profile['hide-friends'];
330 if (Config::get('debug', 'total_ap_delivery')) {
331 // Will be activated in a later step
332 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
334 // For now only send to these contacts:
335 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
338 $data = ['to' => [], 'cc' => [], 'bcc' => []];
340 if ($item['gravity'] == GRAVITY_PARENT) {
341 $actor_profile = APContact::getByURL($item['owner-link']);
343 $actor_profile = APContact::getByURL($item['author-link']);
346 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
348 if (!$item['private']) {
349 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
351 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
353 foreach ($terms as $term) {
354 $profile = APContact::getByURL($term['url'], false);
355 if (!empty($profile)) {
356 $data['to'][] = $profile['url'];
360 $receiver_list = Item::enumeratePermissions($item);
362 foreach ($terms as $term) {
363 $cid = Contact::getIdForURL($term['url'], $item['uid']);
364 if (!empty($cid) && in_array($cid, $receiver_list)) {
365 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
366 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
367 $data['to'][] = $profile['url'];
372 foreach ($receiver_list as $receiver) {
373 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
374 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
375 if ($contact['hidden'] || $always_bcc) {
376 $data['bcc'][] = $profile['url'];
378 $data['cc'][] = $profile['url'];
384 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
385 while ($parent = Item::fetch($parents)) {
386 if ($parent['gravity'] == GRAVITY_PARENT) {
387 $profile = APContact::getByURL($parent['owner-link'], false);
388 if (!empty($profile)) {
389 if ($item['gravity'] != GRAVITY_PARENT) {
390 // Comments to forums are directed to the forum
391 // But comments to forums aren't directed to the followers collection
392 if ($profile['type'] == 'Group') {
393 $data['to'][] = $profile['url'];
395 $data['cc'][] = $profile['url'];
396 if (!$item['private']) {
397 $data['cc'][] = $actor_profile['followers'];
401 // Public thread parent post always are directed to the followes
402 if (!$item['private']) {
403 $data['cc'][] = $actor_profile['followers'];
409 // Don't include data from future posts
410 if ($parent['id'] >= $last_id) {
414 $profile = APContact::getByURL($parent['author-link'], false);
415 if (!empty($profile)) {
416 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
417 $data['to'][] = $profile['url'];
419 $data['cc'][] = $profile['url'];
423 DBA::close($parents);
425 $data['to'] = array_unique($data['to']);
426 $data['cc'] = array_unique($data['cc']);
427 $data['bcc'] = array_unique($data['bcc']);
429 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
430 unset($data['to'][$key]);
433 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
434 unset($data['cc'][$key]);
437 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
438 unset($data['bcc'][$key]);
441 foreach ($data['to'] as $to) {
442 if (($key = array_search($to, $data['cc'])) !== false) {
443 unset($data['cc'][$key]);
446 if (($key = array_search($to, $data['bcc'])) !== false) {
447 unset($data['bcc'][$key]);
451 foreach ($data['cc'] as $cc) {
452 if (($key = array_search($cc, $data['bcc'])) !== false) {
453 unset($data['bcc'][$key]);
457 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
460 unset($receivers['bcc']);
467 * Fetches a list of inboxes of followers of a given user
469 * @param integer $uid User ID
470 * @param boolean $personal fetch personal inboxes
472 * @return array of follower inboxes
473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
474 * @throws \ImagickException
476 public static function fetchTargetInboxesforUser($uid, $personal = false)
480 if (Config::get('debug', 'total_ap_delivery')) {
481 // Will be activated in a later step
482 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
484 // For now only send to these contacts:
485 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
488 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
491 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
494 $contacts = DBA::select('contact', ['url'], $condition);
495 while ($contact = DBA::fetch($contacts)) {
496 if (Network::isUrlBlocked($contact['url'])) {
500 $profile = APContact::getByURL($contact['url'], false);
501 if (!empty($profile)) {
502 if (empty($profile['sharedinbox']) || $personal) {
503 $target = $profile['inbox'];
505 $target = $profile['sharedinbox'];
507 $inboxes[$target] = $target;
510 DBA::close($contacts);
516 * Fetches an array of inboxes for the given item and user
519 * @param integer $uid User ID
520 * @param boolean $personal fetch personal inboxes
521 * @param integer $last_id Last item id for adding receivers
523 * @return array with inboxes
524 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
525 * @throws \ImagickException
527 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
529 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
530 if (empty($permissions)) {
536 if ($item['gravity'] == GRAVITY_ACTIVITY) {
537 $item_profile = APContact::getByURL($item['author-link'], false);
539 $item_profile = APContact::getByURL($item['owner-link'], false);
542 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
543 if (empty($permissions[$element])) {
547 $blindcopy = in_array($element, ['bto', 'bcc']);
549 foreach ($permissions[$element] as $receiver) {
550 if (Network::isUrlBlocked($receiver)) {
554 if ($receiver == $item_profile['followers']) {
555 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
557 $profile = APContact::getByURL($receiver, false);
558 if (!empty($profile)) {
559 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
560 $target = $profile['inbox'];
562 $target = $profile['sharedinbox'];
564 $inboxes[$target] = $target;
574 * Returns the activity type of a given item
578 * @return string with activity type
579 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
580 * @throws \ImagickException
582 private static function getTypeOfItem($item)
586 // Only check for a reshare, if it is a real reshare and no quoted reshare
587 if (strpos($item['body'], "[share") === 0) {
588 $announce = api_share_as_retweet($item);
589 $reshared = !empty($announce['plink']);
594 } elseif ($item['verb'] == ACTIVITY_POST) {
595 if ($item['created'] == $item['edited']) {
600 } elseif ($item['verb'] == ACTIVITY_LIKE) {
602 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
604 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
606 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
608 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
609 $type = 'TentativeAccept';
610 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
620 * Creates the activity or fetches it from the cache
622 * @param integer $item_id
623 * @param boolean $force Force new cache entry
625 * @return array with the activity
628 public static function createCachedActivityFromItem($item_id, $force = false)
630 $cachekey = 'APDelivery:createActivity:' . $item_id;
633 $data = Cache::get($cachekey);
634 if (!is_null($data)) {
639 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
641 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
646 * Creates an activity array for a given item id
648 * @param integer $item_id
649 * @param boolean $object_mode Is the activity item is used inside another object?
651 * @return array of activity
654 public static function createActivityFromItem($item_id, $object_mode = false)
656 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
658 if (!DBA::isResult($item)) {
663 $owner = User::getOwnerDataById($item['uid']);
664 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
667 // Disguise forum posts as reshares. Will later be converted to a real announce
668 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
669 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
674 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
675 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
676 if (DBA::isResult($conversation)) {
677 $data = json_decode($conversation['source']);
683 $type = self::getTypeOfItem($item);
687 $data = ['@context' => ActivityPub::CONTEXT];
689 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
691 } elseif ($item['deleted']) {
698 $data['id'] = $item['uri'] . '#' . $type;
699 $data['type'] = $type;
700 $data['actor'] = $item['owner-link'];
702 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
704 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
706 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
708 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
709 $data['object'] = self::createNote($item);
710 } elseif ($data['type'] == 'Announce') {
711 $data = self::createAnnounce($item, $data);
712 } elseif ($data['type'] == 'Follow') {
713 $data['object'] = $item['parent-uri'];
714 } elseif ($data['type'] == 'Undo') {
715 $data['object'] = self::createActivityFromItem($item_id, true);
717 $data['diaspora:guid'] = $item['guid'];
718 if (!empty($item['signed_text'])) {
719 $data['diaspora:like'] = $item['signed_text'];
721 $data['object'] = $item['thr-parent'];
724 if (!empty($item['contact-uid'])) {
725 $uid = $item['contact-uid'];
730 $owner = User::getOwnerDataById($uid);
732 if (!$object_mode && !empty($owner)) {
733 return LDSignature::sign($data, $owner);
738 /// @todo Create "conversation" entry
742 * Creates an object array for a given item id
744 * @param integer $item_id
746 * @return array with the object data
747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
748 * @throws \ImagickException
750 public static function createObjectFromItemID($item_id)
752 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
754 if (!DBA::isResult($item)) {
758 $data = ['@context' => ActivityPub::CONTEXT];
759 $data = array_merge($data, self::createNote($item));
765 * Creates a location entry for a given item array
769 * @return array with location array
771 private static function createLocation($item)
773 $location = ['type' => 'Place'];
775 if (!empty($item['location'])) {
776 $location['name'] = $item['location'];
781 if (empty($item['coord'])) {
782 $coord = Map::getCoordinates($item['location']);
784 $coords = explode(' ', $item['coord']);
785 if (count($coords) == 2) {
786 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
790 if (!empty($coord['lat']) && !empty($coord['lon'])) {
791 $location['latitude'] = $coord['lat'];
792 $location['longitude'] = $coord['lon'];
799 * Returns a tag array for a given item array
803 * @return array of tags
804 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
806 private static function createTagList($item)
810 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
811 foreach ($terms as $term) {
812 if ($term['type'] == Term::HASHTAG) {
813 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
814 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
815 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
816 $contact = Contact::getDetailsByURL($term['url']);
817 if (!empty($contact['addr'])) {
818 $mention = '@' . $contact['addr'];
820 $mention = '@' . $term['url'];
823 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
830 * Adds attachment data to the JSON document
832 * @param array $item Data of the item that is to be posted
833 * @param string $type Object type
835 * @return array with attachment data
836 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
838 private static function createAttachmentList($item, $type)
842 $arr = explode('[/attach],', $item['attach']);
844 foreach ($arr as $r) {
846 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
848 $attributes = ['type' => 'Document',
849 'mediaType' => $matches[3],
850 'url' => $matches[1],
853 if (trim($matches[4]) != '') {
854 $attributes['name'] = trim($matches[4]);
857 $attachments[] = $attributes;
862 if ($type != 'Note') {
866 // Simplify image codes
867 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
869 // Grab all pictures and create attachments out of them
870 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
871 foreach ($pictures[1] as $picture) {
872 $imgdata = Image::getInfoFromURL($picture);
874 $attachments[] = ['type' => 'Document',
875 'mediaType' => $imgdata['mime'],
886 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
888 * @param array $match Matching values for the callback
889 * @return string Replaced mention
890 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
892 private static function mentionCallback($match)
894 if (empty($match[1])) {
898 $data = Contact::getDetailsByURL($match[1]);
899 if (empty($data['nick'])) {
903 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
907 * Remove image elements and replaces them with links to the image
909 * @param string $body
911 * @return string with replaced elements
913 private static function removePictures($body)
915 // Simplify image codes
916 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
918 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
919 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
925 * Fetches the "context" value for a givem item array from the "conversation" table
929 * @return string with context url
932 private static function fetchContextURLForItem($item)
934 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
935 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
936 $context_uri = $conversation['conversation-href'];
937 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
938 $context_uri = $conversation['conversation-uri'];
940 $context_uri = $item['parent-uri'] . '#context';
946 * Returns if the post contains sensitive content ("nsfw")
948 * @param integer $item_id
953 private static function isSensitive($item_id)
955 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
956 return DBA::exists('term', $condition);
964 * @return array with the event data
965 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
967 public static function createEvent($item)
970 $event['name'] = $item['event-summary'];
971 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
972 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
974 if (!$item['event-nofinish']) {
975 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
978 if (!empty($item['event-location'])) {
979 $item['location'] = $item['event-location'];
980 $event['location'] = self::createLocation($item);
987 * Creates a note/article object array
991 * @return array with the object data
992 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
993 * @throws \ImagickException
995 public static function createNote($item)
997 if ($item['event-type'] == 'event') {
999 } elseif (!empty($item['title'])) {
1005 if ($item['deleted']) {
1006 $type = 'Tombstone';
1010 $data['id'] = $item['uri'];
1011 $data['type'] = $type;
1013 if ($item['deleted']) {
1017 $data['summary'] = null; // Ignore by now
1019 if ($item['uri'] != $item['thr-parent']) {
1020 $data['inReplyTo'] = $item['thr-parent'];
1022 $data['inReplyTo'] = null;
1025 $data['diaspora:guid'] = $item['guid'];
1026 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1028 if ($item['created'] != $item['edited']) {
1029 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1032 $data['url'] = $item['plink'];
1033 $data['attributedTo'] = $item['author-link'];
1034 $data['sensitive'] = self::isSensitive($item['id']);
1035 $data['context'] = self::fetchContextURLForItem($item);
1037 if (!empty($item['title'])) {
1038 $data['name'] = BBCode::toPlaintext($item['title'], false);
1041 $permission_block = self::createPermissionBlockForItem($item, false);
1043 $body = $item['body'];
1045 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1046 $body = self::prependMentions($body, $permission_block);
1049 if ($type == 'Note') {
1050 $body = self::removePictures($body);
1053 if ($type == 'Event') {
1054 $data = array_merge($data, self::createEvent($item));
1056 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1057 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1059 $data['content'] = BBCode::convert($body, false, 7);
1062 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1064 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1065 $data['diaspora:comment'] = $item['signed_text'];
1068 $data['attachment'] = self::createAttachmentList($item, $type);
1069 $data['tag'] = self::createTagList($item);
1071 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1072 $data['location'] = self::createLocation($item);
1075 if (!empty($item['app'])) {
1076 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1079 $data = array_merge($data, $permission_block);
1085 * Creates an announce object entry
1087 * @param array $item
1088 * @param array $data activity data
1090 * @return array with activity data
1091 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1092 * @throws \ImagickException
1094 private static function createAnnounce($item, $data)
1096 $announce = api_share_as_retweet($item);
1097 if (empty($announce['plink'])) {
1098 $data['type'] = 'Create';
1099 $data['object'] = self::createNote($item);
1103 // Fetch the original id of the object
1104 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1105 if (!empty($activity)) {
1106 $ldactivity = JsonLD::compact($activity);
1107 $id = JsonLD::fetchElement($ldactivity, '@id');
1109 $data['object'] = $id;
1114 $data['type'] = 'Create';
1115 $data['object'] = self::createNote($item);
1120 * Creates an activity id for a given contact id
1122 * @param integer $cid Contact ID of target
1124 * @return bool|string activity id
1126 public static function activityIDFromContact($cid)
1128 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1129 if (!DBA::isResult($contact)) {
1133 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1134 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1135 return System::baseUrl() . '/activity/' . $uuid;
1139 * Transmits a contact suggestion to a given inbox
1141 * @param integer $uid User ID
1142 * @param string $inbox Target inbox
1143 * @param integer $suggestion_id Suggestion ID
1145 * @return boolean was the transmission successful?
1146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1148 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1150 $owner = User::getOwnerDataById($uid);
1152 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1154 $data = ['@context' => ActivityPub::CONTEXT,
1155 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1156 'type' => 'Announce',
1157 'actor' => $owner['url'],
1158 'object' => $suggestion['url'],
1159 'content' => $suggestion['note'],
1160 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1161 'to' => [ActivityPub::PUBLIC_COLLECTION],
1164 $signed = LDSignature::sign($data, $owner);
1166 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1167 return HTTPSignature::transmit($signed, $inbox, $uid);
1171 * Transmits a profile relocation to a given inbox
1173 * @param integer $uid User ID
1174 * @param string $inbox Target inbox
1176 * @return boolean was the transmission successful?
1177 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1179 public static function sendProfileRelocation($uid, $inbox)
1181 $owner = User::getOwnerDataById($uid);
1183 $data = ['@context' => ActivityPub::CONTEXT,
1184 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1185 'type' => 'dfrn:relocate',
1186 'actor' => $owner['url'],
1187 'object' => $owner['url'],
1188 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1189 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1190 'to' => [ActivityPub::PUBLIC_COLLECTION],
1193 $signed = LDSignature::sign($data, $owner);
1195 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1196 return HTTPSignature::transmit($signed, $inbox, $uid);
1200 * Transmits a profile deletion to a given inbox
1202 * @param integer $uid User ID
1203 * @param string $inbox Target inbox
1205 * @return boolean was the transmission successful?
1206 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1208 public static function sendProfileDeletion($uid, $inbox)
1210 $owner = User::getOwnerDataById($uid);
1212 if (empty($owner)) {
1213 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1217 if (empty($owner['uprvkey'])) {
1218 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1222 $data = ['@context' => ActivityPub::CONTEXT,
1223 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1225 'actor' => $owner['url'],
1226 'object' => $owner['url'],
1227 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1228 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1229 'to' => [ActivityPub::PUBLIC_COLLECTION],
1232 $signed = LDSignature::sign($data, $owner);
1234 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1235 return HTTPSignature::transmit($signed, $inbox, $uid);
1239 * Transmits a profile change to a given inbox
1241 * @param integer $uid User ID
1242 * @param string $inbox Target inbox
1244 * @return boolean was the transmission successful?
1245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1246 * @throws \ImagickException
1248 public static function sendProfileUpdate($uid, $inbox)
1250 $owner = User::getOwnerDataById($uid);
1251 $profile = APContact::getByURL($owner['url']);
1253 $data = ['@context' => ActivityPub::CONTEXT,
1254 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1256 'actor' => $owner['url'],
1257 'object' => self::getProfile($uid),
1258 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1259 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1260 'to' => [$profile['followers']],
1263 $signed = LDSignature::sign($data, $owner);
1265 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1266 return HTTPSignature::transmit($signed, $inbox, $uid);
1270 * Transmits a given activity to a target
1272 * @param string $activity Type name
1273 * @param string $target Target profile
1274 * @param integer $uid User ID
1276 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1277 * @throws \ImagickException
1278 * @throws \Exception
1280 public static function sendActivity($activity, $target, $uid, $id = '')
1282 $profile = APContact::getByURL($target);
1284 $owner = User::getOwnerDataById($uid);
1287 $id = System::baseUrl() . '/activity/' . System::createGUID();
1290 $data = ['@context' => ActivityPub::CONTEXT,
1292 'type' => $activity,
1293 'actor' => $owner['url'],
1294 'object' => $profile['url'],
1295 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1296 'to' => [$profile['url']]];
1298 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1300 $signed = LDSignature::sign($data, $owner);
1301 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1305 * Transmits a "follow object" activity to a target
1306 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1308 * @param string $object Object URL
1309 * @param string $target Target profile
1310 * @param integer $uid User ID
1312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1313 * @throws \ImagickException
1314 * @throws \Exception
1316 public static function sendFollowObject($object, $target, $uid = 0)
1318 $profile = APContact::getByURL($target);
1321 // Fetch the list of administrators
1322 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1324 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1325 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1326 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1327 $uid = $first_user['uid'];
1330 $condition = ['verb' => ACTIVITY_FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1331 'author-id' => Contact::getPublicIdByUserId($uid)];
1332 if (Item::exists($condition)) {
1333 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1337 $owner = User::getOwnerDataById($uid);
1339 $data = ['@context' => ActivityPub::CONTEXT,
1340 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1342 'actor' => $owner['url'],
1343 'object' => $object,
1344 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1345 'to' => [$profile['url']]];
1347 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1349 $signed = LDSignature::sign($data, $owner);
1350 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1354 * Transmit a message that the contact request had been accepted
1356 * @param string $target Target profile
1358 * @param integer $uid User ID
1359 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1360 * @throws \ImagickException
1362 public static function sendContactAccept($target, $id, $uid)
1364 $profile = APContact::getByURL($target);
1366 $owner = User::getOwnerDataById($uid);
1367 $data = ['@context' => ActivityPub::CONTEXT,
1368 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1370 'actor' => $owner['url'],
1371 'object' => ['id' => $id, 'type' => 'Follow',
1372 'actor' => $profile['url'],
1373 'object' => $owner['url']],
1374 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1375 'to' => [$profile['url']]];
1377 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1379 $signed = LDSignature::sign($data, $owner);
1380 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1384 * Reject a contact request or terminates the contact relation
1386 * @param string $target Target profile
1388 * @param integer $uid User ID
1389 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1390 * @throws \ImagickException
1392 public static function sendContactReject($target, $id, $uid)
1394 $profile = APContact::getByURL($target);
1396 $owner = User::getOwnerDataById($uid);
1397 $data = ['@context' => ActivityPub::CONTEXT,
1398 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1400 'actor' => $owner['url'],
1401 'object' => ['id' => $id, 'type' => 'Follow',
1402 'actor' => $profile['url'],
1403 'object' => $owner['url']],
1404 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1405 'to' => [$profile['url']]];
1407 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1409 $signed = LDSignature::sign($data, $owner);
1410 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1414 * Transmits a message that we don't want to follow this contact anymore
1416 * @param string $target Target profile
1417 * @param integer $uid User ID
1418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1419 * @throws \ImagickException
1420 * @throws \Exception
1422 public static function sendContactUndo($target, $cid, $uid)
1424 $profile = APContact::getByURL($target);
1426 $object_id = self::activityIDFromContact($cid);
1427 if (empty($object_id)) {
1431 $id = System::baseUrl() . '/activity/' . System::createGUID();
1433 $owner = User::getOwnerDataById($uid);
1434 $data = ['@context' => ActivityPub::CONTEXT,
1437 'actor' => $owner['url'],
1438 'object' => ['id' => $object_id, 'type' => 'Follow',
1439 'actor' => $owner['url'],
1440 'object' => $profile['url']],
1441 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1442 'to' => [$profile['url']]];
1444 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1446 $signed = LDSignature::sign($data, $owner);
1447 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1450 private static function prependMentions($body, array $permission_block)
1452 if (Config::get('system', 'disable_implicit_mentions')) {
1458 foreach ($permission_block['to'] as $profile_url) {
1459 $profile = Contact::getDetailsByURL($profile_url);
1460 if (!empty($profile['addr'])
1461 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1462 && !strstr($body, $profile['addr'])
1463 && !strstr($body, $profile_url)
1465 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1469 $mentions[] = $body;
1471 return implode(' ', $mentions);