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\Config;
10 use Friendica\Core\Logger;
11 use Friendica\Core\System;
12 use Friendica\Util\HTTPSignature;
13 use Friendica\Core\Protocol;
14 use Friendica\Model\Conversation;
15 use Friendica\Model\Contact;
16 use Friendica\Model\APContact;
17 use Friendica\Model\Item;
18 use Friendica\Model\Term;
19 use Friendica\Model\User;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Content\Text\BBCode;
22 use Friendica\Util\JsonLD;
23 use Friendica\Util\LDSignature;
24 use Friendica\Model\Profile;
25 use Friendica\Object\Image;
26 use Friendica\Protocol\ActivityPub;
27 use Friendica\Core\Cache;
28 use Friendica\Util\Map;
29 use Friendica\Util\Network;
31 require_once 'include/api.php';
32 require_once 'mod/share.php';
35 * @brief ActivityPub Transmitter Protocol class
43 * collects the lost of followers of the given owner
45 * @param array $owner Owner array
46 * @param integer $page Page number
48 * @return array of owners
49 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
51 public static function getFollowers($owner, $page = null)
53 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
54 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
55 $count = DBA::count('contact', $condition);
57 $data = ['@context' => ActivityPub::CONTEXT];
58 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
59 $data['type'] = 'OrderedCollection';
60 $data['totalItems'] = $count;
62 // When we hide our friends we will only show the pure number but don't allow more.
63 $profile = Profile::getByUID($owner['uid']);
64 if (!empty($profile['hide-friends'])) {
69 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
73 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
74 while ($contact = DBA::fetch($contacts)) {
75 $list[] = $contact['url'];
79 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
82 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
84 $data['orderedItems'] = $list;
91 * Create list of following contacts
93 * @param array $owner Owner array
94 * @param integer $page Page numbe
96 * @return array of following contacts
97 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
99 public static function getFollowing($owner, $page = null)
101 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
102 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
103 $count = DBA::count('contact', $condition);
105 $data = ['@context' => ActivityPub::CONTEXT];
106 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
107 $data['type'] = 'OrderedCollection';
108 $data['totalItems'] = $count;
110 // When we hide our friends we will only show the pure number but don't allow more.
111 $profile = Profile::getByUID($owner['uid']);
112 if (!empty($profile['hide-friends'])) {
117 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
121 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
122 while ($contact = DBA::fetch($contacts)) {
123 $list[] = $contact['url'];
127 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
130 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
132 $data['orderedItems'] = $list;
139 * Public posts for the given owner
141 * @param array $owner Owner array
142 * @param integer $page Page numbe
144 * @return array of posts
145 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
146 * @throws \ImagickException
148 public static function getOutbox($owner, $page = null)
150 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
152 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
153 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
154 'deleted' => false, 'visible' => true];
155 $count = DBA::count('item', $condition);
157 $data = ['@context' => ActivityPub::CONTEXT];
158 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
159 $data['type'] = 'OrderedCollection';
160 $data['totalItems'] = $count;
163 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
167 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
169 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
170 while ($item = Item::fetch($items)) {
171 $object = self::createObjectFromItemID($item['id']);
172 unset($object['@context']);
177 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
180 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
182 $data['orderedItems'] = $list;
189 * Return the ActivityPub profile of the given user
191 * @param integer $uid User ID
192 * @return array with profile data
193 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
195 public static function getProfile($uid)
197 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
198 'account_removed' => false, 'verified' => true];
199 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
200 $user = DBA::selectFirst('user', $fields, $condition);
201 if (!DBA::isResult($user)) {
205 $fields = ['locality', 'region', 'country-name'];
206 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
207 if (!DBA::isResult($profile)) {
211 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
212 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
213 if (!DBA::isResult($contact)) {
217 // On old installations and never changed contacts this might not be filled
218 if (empty($contact['avatar'])) {
219 $contact['avatar'] = $contact['photo'];
222 $data = ['@context' => ActivityPub::CONTEXT];
223 $data['id'] = $contact['url'];
224 $data['diaspora:guid'] = $user['guid'];
225 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
226 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
227 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
228 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
229 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
230 $data['preferredUsername'] = $user['nickname'];
231 $data['name'] = $contact['name'];
232 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
233 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
234 $data['summary'] = $contact['about'];
235 $data['url'] = $contact['url'];
236 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
237 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
238 'owner' => $contact['url'],
239 'publicKeyPem' => $user['pubkey']];
240 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
241 $data['icon'] = ['type' => 'Image',
242 'url' => $contact['avatar']];
244 // tags: https://kitty.town/@inmysocks/100656097926961126.json
249 * Returns an array with permissions of a given item array
253 * @return array with permissions
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 * @throws \ImagickException
257 private static function fetchPermissionBlockFromConversation($item)
259 if (empty($item['thr-parent'])) {
263 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
264 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
265 if (!DBA::isResult($conversation)) {
269 $activity = json_decode($conversation['source'], true);
271 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
272 $profile = APContact::getByURL($actor);
274 $item_profile = APContact::getByURL($item['author-link']);
275 $exclude[] = $item['author-link'];
277 if ($item['gravity'] == GRAVITY_PARENT) {
278 $exclude[] = $item['owner-link'];
281 $permissions['to'][] = $actor;
283 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
284 if (empty($activity[$element])) {
287 if (is_string($activity[$element])) {
288 $activity[$element] = [$activity[$element]];
291 foreach ($activity[$element] as $receiver) {
292 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
293 $permissions[$element][] = $item_profile['followers'];
294 } elseif (!in_array($receiver, $exclude)) {
295 $permissions[$element][] = $receiver;
303 * Creates an array of permissions from an item thread
306 * @param boolean $blindcopy
307 * @param boolean $last_id
309 * @return array with permission data
310 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
311 * @throws \ImagickException
313 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
316 $last_id = $item['id'];
321 // Check if we should always deliver our stuff via BCC
322 if (!empty($item['uid'])) {
323 $profile = Profile::getByUID($item['uid']);
324 if (!empty($profile)) {
325 $always_bcc = $profile['hide-friends'];
329 if (Config::get('debug', 'total_ap_delivery')) {
330 // Will be activated in a later step
331 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
333 // For now only send to these contacts:
334 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
337 $data = ['to' => [], 'cc' => [], 'bcc' => []];
339 if ($item['gravity'] == GRAVITY_PARENT) {
340 $actor_profile = APContact::getByURL($item['owner-link']);
342 $actor_profile = APContact::getByURL($item['author-link']);
345 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
347 if (!$item['private']) {
348 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
350 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
352 foreach ($terms as $term) {
353 $profile = APContact::getByURL($term['url'], false);
354 if (!empty($profile)) {
355 $data['to'][] = $profile['url'];
359 $receiver_list = Item::enumeratePermissions($item);
361 foreach ($terms as $term) {
362 $cid = Contact::getIdForURL($term['url'], $item['uid']);
363 if (!empty($cid) && in_array($cid, $receiver_list)) {
364 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
365 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
366 $data['to'][] = $profile['url'];
371 foreach ($receiver_list as $receiver) {
372 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
373 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
374 if ($contact['hidden'] || $always_bcc) {
375 $data['bcc'][] = $profile['url'];
377 $data['cc'][] = $profile['url'];
383 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
384 while ($parent = Item::fetch($parents)) {
385 if ($parent['gravity'] == GRAVITY_PARENT) {
386 $profile = APContact::getByURL($parent['owner-link'], false);
387 if (!empty($profile)) {
388 if ($item['gravity'] != GRAVITY_PARENT) {
389 // Comments to forums are directed to the forum
390 // But comments to forums aren't directed to the followers collection
391 if ($profile['type'] == 'Group') {
392 $data['to'][] = $profile['url'];
394 $data['cc'][] = $profile['url'];
395 if (!$item['private']) {
396 $data['cc'][] = $actor_profile['followers'];
400 // Public thread parent post always are directed to the followes
401 if (!$item['private']) {
402 $data['cc'][] = $actor_profile['followers'];
408 // Don't include data from future posts
409 if ($parent['id'] >= $last_id) {
413 $profile = APContact::getByURL($parent['author-link'], false);
414 if (!empty($profile)) {
415 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
416 $data['to'][] = $profile['url'];
418 $data['cc'][] = $profile['url'];
422 DBA::close($parents);
424 $data['to'] = array_unique($data['to']);
425 $data['cc'] = array_unique($data['cc']);
426 $data['bcc'] = array_unique($data['bcc']);
428 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
429 unset($data['to'][$key]);
432 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
433 unset($data['cc'][$key]);
436 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
437 unset($data['bcc'][$key]);
440 foreach ($data['to'] as $to) {
441 if (($key = array_search($to, $data['cc'])) !== false) {
442 unset($data['cc'][$key]);
445 if (($key = array_search($to, $data['bcc'])) !== false) {
446 unset($data['bcc'][$key]);
450 foreach ($data['cc'] as $cc) {
451 if (($key = array_search($cc, $data['bcc'])) !== false) {
452 unset($data['bcc'][$key]);
456 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
459 unset($receivers['bcc']);
466 * Fetches a list of inboxes of followers of a given user
468 * @param integer $uid User ID
469 * @param boolean $personal fetch personal inboxes
471 * @return array of follower inboxes
472 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
473 * @throws \ImagickException
475 public static function fetchTargetInboxesforUser($uid, $personal = false)
479 if (Config::get('debug', 'total_ap_delivery')) {
480 // Will be activated in a later step
481 $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
483 // For now only send to these contacts:
484 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
487 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
490 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
493 $contacts = DBA::select('contact', ['url'], $condition);
494 while ($contact = DBA::fetch($contacts)) {
495 if (Network::isUrlBlocked($contact['url'])) {
499 $profile = APContact::getByURL($contact['url'], false);
500 if (!empty($profile)) {
501 if (empty($profile['sharedinbox']) || $personal) {
502 $target = $profile['inbox'];
504 $target = $profile['sharedinbox'];
506 $inboxes[$target] = $target;
509 DBA::close($contacts);
515 * Fetches an array of inboxes for the given item and user
518 * @param integer $uid User ID
519 * @param boolean $personal fetch personal inboxes
520 * @param integer $last_id Last item id for adding receivers
522 * @return array with inboxes
523 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
524 * @throws \ImagickException
526 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
528 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
529 if (empty($permissions)) {
535 if ($item['gravity'] == GRAVITY_ACTIVITY) {
536 $item_profile = APContact::getByURL($item['author-link'], false);
538 $item_profile = APContact::getByURL($item['owner-link'], false);
541 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
542 if (empty($permissions[$element])) {
546 $blindcopy = in_array($element, ['bto', 'bcc']);
548 foreach ($permissions[$element] as $receiver) {
549 if (Network::isUrlBlocked($receiver)) {
553 if ($receiver == $item_profile['followers']) {
554 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
556 $profile = APContact::getByURL($receiver, false);
557 if (!empty($profile)) {
558 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
559 $target = $profile['inbox'];
561 $target = $profile['sharedinbox'];
563 $inboxes[$target] = $target;
573 * Returns the activity type of a given item
577 * @return string with activity type
578 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
579 * @throws \ImagickException
581 private static function getTypeOfItem($item)
585 // Only check for a reshare, if it is a real reshare and no quoted reshare
586 if (strpos($item['body'], "[share") === 0) {
587 $announce = api_share_as_retweet($item);
588 $reshared = !empty($announce['plink']);
593 } elseif ($item['verb'] == ACTIVITY_POST) {
594 if ($item['created'] == $item['edited']) {
599 } elseif ($item['verb'] == ACTIVITY_LIKE) {
601 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
603 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
605 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
607 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
608 $type = 'TentativeAccept';
609 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
619 * Creates the activity or fetches it from the cache
621 * @param integer $item_id
622 * @param boolean $force Force new cache entry
624 * @return array with the activity
627 public static function createCachedActivityFromItem($item_id, $force = false)
629 $cachekey = 'APDelivery:createActivity:' . $item_id;
632 $data = Cache::get($cachekey);
633 if (!is_null($data)) {
638 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
640 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
645 * Creates an activity array for a given item id
647 * @param integer $item_id
648 * @param boolean $object_mode Is the activity item is used inside another object?
650 * @return array of activity
653 public static function createActivityFromItem($item_id, $object_mode = false)
655 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
657 if (!DBA::isResult($item)) {
662 $owner = User::getOwnerDataById($item['uid']);
663 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
666 // Disguise forum posts as reshares. Will later be converted to a real announce
667 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
668 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
673 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
674 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
675 if (DBA::isResult($conversation)) {
676 $data = json_decode($conversation['source']);
682 $type = self::getTypeOfItem($item);
686 $data = ['@context' => ActivityPub::CONTEXT];
688 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
690 } elseif ($item['deleted']) {
697 $data['id'] = $item['uri'] . '#' . $type;
698 $data['type'] = $type;
699 $data['actor'] = $item['owner-link'];
701 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
703 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
705 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
707 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
708 $data['object'] = self::createNote($item);
709 } elseif ($data['type'] == 'Announce') {
710 $data = self::createAnnounce($item, $data);
711 } elseif ($data['type'] == 'Follow') {
712 $data['object'] = $item['parent-uri'];
713 } elseif ($data['type'] == 'Undo') {
714 $data['object'] = self::createActivityFromItem($item_id, true);
716 $data['diaspora:guid'] = $item['guid'];
717 if (!empty($item['signed_text'])) {
718 $data['diaspora:like'] = $item['signed_text'];
720 $data['object'] = $item['thr-parent'];
723 if (!empty($item['contact-uid'])) {
724 $uid = $item['contact-uid'];
729 $owner = User::getOwnerDataById($uid);
731 if (!$object_mode && !empty($owner)) {
732 return LDSignature::sign($data, $owner);
737 /// @todo Create "conversation" entry
741 * Creates an object array for a given item id
743 * @param integer $item_id
745 * @return array with the object data
746 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
747 * @throws \ImagickException
749 public static function createObjectFromItemID($item_id)
751 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
753 if (!DBA::isResult($item)) {
757 $data = ['@context' => ActivityPub::CONTEXT];
758 $data = array_merge($data, self::createNote($item));
764 * Creates a location entry for a given item array
768 * @return array with location array
770 private static function createLocation($item)
772 $location = ['type' => 'Place'];
774 if (!empty($item['location'])) {
775 $location['name'] = $item['location'];
780 if (empty($item['coord'])) {
781 $coord = Map::getCoordinates($item['location']);
783 $coords = explode(' ', $item['coord']);
784 if (count($coords) == 2) {
785 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
789 if (!empty($coord['lat']) && !empty($coord['lon'])) {
790 $location['latitude'] = $coord['lat'];
791 $location['longitude'] = $coord['lon'];
798 * Returns a tag array for a given item array
802 * @return array of tags
803 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
805 private static function createTagList($item)
809 $terms = Term::tagArrayFromItemId($item['id']);
810 foreach ($terms as $term) {
811 if ($term['type'] == TERM_HASHTAG) {
812 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
813 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
814 } elseif ($term['type'] == TERM_MENTION) {
815 $contact = Contact::getDetailsByURL($term['url']);
816 if (!empty($contact['addr'])) {
817 $mention = '@' . $contact['addr'];
819 $mention = '@' . $term['url'];
822 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
829 * Adds attachment data to the JSON document
831 * @param array $item Data of the item that is to be posted
832 * @param string $type Object type
834 * @return array with attachment data
835 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
837 private static function createAttachmentList($item, $type)
841 $arr = explode('[/attach],', $item['attach']);
843 foreach ($arr as $r) {
845 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
847 $attributes = ['type' => 'Document',
848 'mediaType' => $matches[3],
849 'url' => $matches[1],
852 if (trim($matches[4]) != '') {
853 $attributes['name'] = trim($matches[4]);
856 $attachments[] = $attributes;
861 if ($type != 'Note') {
865 // Simplify image codes
866 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
868 // Grab all pictures and create attachments out of them
869 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
870 foreach ($pictures[1] as $picture) {
871 $imgdata = Image::getInfoFromURL($picture);
873 $attachments[] = ['type' => 'Document',
874 'mediaType' => $imgdata['mime'],
885 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
887 * @param array $match Matching values for the callback
888 * @return string Replaced mention
889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
891 private static function mentionCallback($match)
893 if (empty($match[1])) {
897 $data = Contact::getDetailsByURL($match[1]);
898 if (empty($data) || empty($data['nick'])) {
902 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
906 * Remove image elements and replaces them with links to the image
908 * @param string $body
910 * @return string with replaced elements
912 private static function removePictures($body)
914 // Simplify image codes
915 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
917 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
918 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
924 * Fetches the "context" value for a givem item array from the "conversation" table
928 * @return string with context url
931 private static function fetchContextURLForItem($item)
933 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
934 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
935 $context_uri = $conversation['conversation-href'];
936 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
937 $context_uri = $conversation['conversation-uri'];
939 $context_uri = $item['parent-uri'] . '#context';
945 * Returns if the post contains sensitive content ("nsfw")
947 * @param integer $item_id
952 private static function isSensitive($item_id)
954 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
955 return DBA::exists('term', $condition);
963 * @return array with the event data
964 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
966 public static function createEvent($item)
969 $event['name'] = $item['event-summary'];
970 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
971 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
973 if (!$item['event-nofinish']) {
974 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
977 if (!empty($item['event-location'])) {
978 $item['location'] = $item['event-location'];
979 $event['location'] = self::createLocation($item);
986 * Creates a note/article object array
990 * @return array with the object data
991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
992 * @throws \ImagickException
994 public static function createNote($item)
996 if ($item['event-type'] == 'event') {
998 } elseif (!empty($item['title'])) {
1004 if ($item['deleted']) {
1005 $type = 'Tombstone';
1009 $data['id'] = $item['uri'];
1010 $data['type'] = $type;
1012 if ($item['deleted']) {
1016 $data['summary'] = null; // Ignore by now
1018 if ($item['uri'] != $item['thr-parent']) {
1019 $data['inReplyTo'] = $item['thr-parent'];
1021 $data['inReplyTo'] = null;
1024 $data['diaspora:guid'] = $item['guid'];
1025 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1027 if ($item['created'] != $item['edited']) {
1028 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1031 $data['url'] = $item['plink'];
1032 $data['attributedTo'] = $item['author-link'];
1033 $data['sensitive'] = self::isSensitive($item['id']);
1034 $data['context'] = self::fetchContextURLForItem($item);
1036 if (!empty($item['title'])) {
1037 $data['name'] = BBCode::toPlaintext($item['title'], false);
1040 $body = $item['body'];
1042 if ($type == 'Note') {
1043 $body = self::removePictures($body);
1046 if ($type == 'Event') {
1047 $data = array_merge($data, self::createEvent($item));
1049 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1050 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1052 $data['content'] = BBCode::convert($body, false, 7);
1055 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1057 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1058 $data['diaspora:comment'] = $item['signed_text'];
1061 $data['attachment'] = self::createAttachmentList($item, $type);
1062 $data['tag'] = self::createTagList($item);
1064 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1065 $data['location'] = self::createLocation($item);
1068 if (!empty($item['app'])) {
1069 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1072 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1078 * Creates an announce object entry
1080 * @param array $item
1081 * @param array $data activity data
1083 * @return array with activity data
1084 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1085 * @throws \ImagickException
1087 private static function createAnnounce($item, $data)
1089 $announce = api_share_as_retweet($item);
1090 if (empty($announce['plink'])) {
1091 $data['type'] = 'Create';
1092 $data['object'] = self::createNote($item);
1096 // Fetch the original id of the object
1097 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1098 if (!empty($activity)) {
1099 $ldactivity = JsonLD::compact($activity);
1100 $id = JsonLD::fetchElement($ldactivity, '@id');
1102 $data['object'] = $id;
1107 $data['type'] = 'Create';
1108 $data['object'] = self::createNote($item);
1113 * Creates an activity id for a given contact id
1115 * @param integer $cid Contact ID of target
1117 * @return bool|string activity id
1119 public static function activityIDFromContact($cid)
1121 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1122 if (!DBA::isResult($contact)) {
1126 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1127 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1128 return System::baseUrl() . '/activity/' . $uuid;
1132 * Transmits a contact suggestion to a given inbox
1134 * @param integer $uid User ID
1135 * @param string $inbox Target inbox
1136 * @param integer $suggestion_id Suggestion ID
1138 * @return boolean was the transmission successful?
1139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1141 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1143 $owner = User::getOwnerDataById($uid);
1145 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1147 $data = ['@context' => ActivityPub::CONTEXT,
1148 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1149 'type' => 'Announce',
1150 'actor' => $owner['url'],
1151 'object' => $suggestion['url'],
1152 'content' => $suggestion['note'],
1153 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1154 'to' => [ActivityPub::PUBLIC_COLLECTION],
1157 $signed = LDSignature::sign($data, $owner);
1159 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1160 return HTTPSignature::transmit($signed, $inbox, $uid);
1164 * Transmits a profile relocation to a given inbox
1166 * @param integer $uid User ID
1167 * @param string $inbox Target inbox
1169 * @return boolean was the transmission successful?
1170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1172 public static function sendProfileRelocation($uid, $inbox)
1174 $owner = User::getOwnerDataById($uid);
1176 $data = ['@context' => ActivityPub::CONTEXT,
1177 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1178 'type' => 'dfrn:relocate',
1179 'actor' => $owner['url'],
1180 'object' => $owner['url'],
1181 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1182 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1183 'to' => [ActivityPub::PUBLIC_COLLECTION],
1186 $signed = LDSignature::sign($data, $owner);
1188 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1189 return HTTPSignature::transmit($signed, $inbox, $uid);
1193 * Transmits a profile deletion to a given inbox
1195 * @param integer $uid User ID
1196 * @param string $inbox Target inbox
1198 * @return boolean was the transmission successful?
1199 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1201 public static function sendProfileDeletion($uid, $inbox)
1203 $owner = User::getOwnerDataById($uid);
1205 $data = ['@context' => ActivityPub::CONTEXT,
1206 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1208 'actor' => $owner['url'],
1209 'object' => $owner['url'],
1210 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1211 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1212 'to' => [ActivityPub::PUBLIC_COLLECTION],
1215 $signed = LDSignature::sign($data, $owner);
1217 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1218 return HTTPSignature::transmit($signed, $inbox, $uid);
1222 * Transmits a profile change to a given inbox
1224 * @param integer $uid User ID
1225 * @param string $inbox Target inbox
1227 * @return boolean was the transmission successful?
1228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1229 * @throws \ImagickException
1231 public static function sendProfileUpdate($uid, $inbox)
1233 $owner = User::getOwnerDataById($uid);
1234 $profile = APContact::getByURL($owner['url']);
1236 $data = ['@context' => ActivityPub::CONTEXT,
1237 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1239 'actor' => $owner['url'],
1240 'object' => self::getProfile($uid),
1241 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1242 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1243 'to' => [$profile['followers']],
1246 $signed = LDSignature::sign($data, $owner);
1248 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1249 return HTTPSignature::transmit($signed, $inbox, $uid);
1253 * Transmits a given activity to a target
1255 * @param string $activity Type name
1256 * @param string $target Target profile
1257 * @param integer $uid User ID
1259 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1260 * @throws \ImagickException
1261 * @throws \Exception
1263 public static function sendActivity($activity, $target, $uid, $id = '')
1265 $profile = APContact::getByURL($target);
1267 $owner = User::getOwnerDataById($uid);
1270 $id = System::baseUrl() . '/activity/' . System::createGUID();
1273 $data = ['@context' => ActivityPub::CONTEXT,
1275 'type' => $activity,
1276 'actor' => $owner['url'],
1277 'object' => $profile['url'],
1278 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1279 'to' => [$profile['url']]];
1281 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1283 $signed = LDSignature::sign($data, $owner);
1284 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1288 * Transmits a "follow object" activity to a target
1289 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1291 * @param string $object Object URL
1292 * @param string $target Target profile
1293 * @param integer $uid User ID
1295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1296 * @throws \ImagickException
1297 * @throws \Exception
1299 public static function sendFollowObject($object, $target, $uid = 0)
1301 $profile = APContact::getByURL($target);
1304 // Fetch the list of administrators
1305 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1307 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1308 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1309 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1310 $uid = $first_user['uid'];
1313 $owner = User::getOwnerDataById($uid);
1315 $data = ['@context' => ActivityPub::CONTEXT,
1316 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1318 'actor' => $owner['url'],
1319 'object' => $object,
1320 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1321 'to' => [$profile['url']]];
1323 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1325 $signed = LDSignature::sign($data, $owner);
1326 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1330 * Transmit a message that the contact request had been accepted
1332 * @param string $target Target profile
1334 * @param integer $uid User ID
1335 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1336 * @throws \ImagickException
1338 public static function sendContactAccept($target, $id, $uid)
1340 $profile = APContact::getByURL($target);
1342 $owner = User::getOwnerDataById($uid);
1343 $data = ['@context' => ActivityPub::CONTEXT,
1344 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1346 'actor' => $owner['url'],
1347 'object' => ['id' => $id, 'type' => 'Follow',
1348 'actor' => $profile['url'],
1349 'object' => $owner['url']],
1350 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1351 'to' => [$profile['url']]];
1353 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1355 $signed = LDSignature::sign($data, $owner);
1356 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1360 * Reject a contact request or terminates the contact relation
1362 * @param string $target Target profile
1364 * @param integer $uid User ID
1365 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1366 * @throws \ImagickException
1368 public static function sendContactReject($target, $id, $uid)
1370 $profile = APContact::getByURL($target);
1372 $owner = User::getOwnerDataById($uid);
1373 $data = ['@context' => ActivityPub::CONTEXT,
1374 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1376 'actor' => $owner['url'],
1377 'object' => ['id' => $id, 'type' => 'Follow',
1378 'actor' => $profile['url'],
1379 'object' => $owner['url']],
1380 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1381 'to' => [$profile['url']]];
1383 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1385 $signed = LDSignature::sign($data, $owner);
1386 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1390 * Transmits a message that we don't want to follow this contact anymore
1392 * @param string $target Target profile
1393 * @param integer $uid User ID
1394 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1395 * @throws \ImagickException
1396 * @throws \Exception
1398 public static function sendContactUndo($target, $cid, $uid)
1400 $profile = APContact::getByURL($target);
1402 $object_id = self::activityIDFromContact($cid);
1403 if (empty($object_id)) {
1407 $id = System::baseUrl() . '/activity/' . System::createGUID();
1409 $owner = User::getOwnerDataById($uid);
1410 $data = ['@context' => ActivityPub::CONTEXT,
1413 'actor' => $owner['url'],
1414 'object' => ['id' => $object_id, 'type' => 'Follow',
1415 'actor' => $owner['url'],
1416 'object' => $profile['url']],
1417 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1418 'to' => [$profile['url']]];
1420 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1422 $signed = LDSignature::sign($data, $owner);
1423 HTTPSignature::transmit($signed, $profile['inbox'], $uid);