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\Core\Config;
25 use Friendica\Object\Image;
26 use Friendica\Protocol\ActivityPub;
27 use Friendica\Protocol\Diaspora;
28 use Friendica\Core\Cache;
29 use Friendica\Util\Map;
30 use Friendica\Util\Network;
32 require_once 'include/api.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'], [Contact::PAGE_NORMAL, Contact::PAGE_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 // Will be activated in a later step
330 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
332 // For now only send to these contacts:
333 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
335 $data = ['to' => [], 'cc' => [], 'bcc' => []];
337 $actor_profile = APContact::getByURL($item['author-link']);
339 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
341 if (!$item['private']) {
342 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
344 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
345 if (!empty($actor_profile['followers'])) {
346 $data['cc'][] = $actor_profile['followers'];
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);
360 foreach ($terms as $term) {
361 $cid = Contact::getIdForURL($term['url'], $item['uid']);
362 if (!empty($cid) && in_array($cid, $receiver_list)) {
363 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
364 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
365 $data['to'][] = $profile['url'];
370 foreach ($receiver_list as $receiver) {
371 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
372 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
373 if ($contact['hidden'] || $always_bcc) {
374 $data['bcc'][] = $profile['url'];
376 $data['cc'][] = $profile['url'];
382 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
383 while ($parent = Item::fetch($parents)) {
384 // Don't include data from future posts
385 if ($parent['id'] >= $last_id) {
389 $profile = APContact::getByURL($parent['author-link'], false);
390 if (!empty($profile)) {
391 if ($parent['uri'] == $item['thr-parent']) {
392 $data['to'][] = $profile['url'];
394 $data['cc'][] = $profile['url'];
398 if ($item['gravity'] != GRAVITY_PARENT) {
402 $profile = APContact::getByURL($parent['owner-link'], false);
403 if (!empty($profile)) {
404 $data['cc'][] = $profile['url'];
407 DBA::close($parents);
409 $data['to'] = array_unique($data['to']);
410 $data['cc'] = array_unique($data['cc']);
411 $data['bcc'] = array_unique($data['bcc']);
413 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
414 unset($data['to'][$key]);
417 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
418 unset($data['cc'][$key]);
421 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
422 unset($data['bcc'][$key]);
425 foreach ($data['to'] as $to) {
426 if (($key = array_search($to, $data['cc'])) !== false) {
427 unset($data['cc'][$key]);
430 if (($key = array_search($to, $data['bcc'])) !== false) {
431 unset($data['bcc'][$key]);
435 foreach ($data['cc'] as $cc) {
436 if (($key = array_search($cc, $data['bcc'])) !== false) {
437 unset($data['bcc'][$key]);
441 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
444 unset($receivers['bcc']);
451 * Fetches a list of inboxes of followers of a given user
453 * @param integer $uid User ID
454 * @param boolean $personal fetch personal inboxes
456 * @return array of follower inboxes
457 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
458 * @throws \ImagickException
460 public static function fetchTargetInboxesforUser($uid, $personal = false)
464 // Will be activated in a later step
465 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
467 // For now only send to these contacts:
468 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
470 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
473 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
476 $contacts = DBA::select('contact', ['url'], $condition);
477 while ($contact = DBA::fetch($contacts)) {
478 if (Network::isUrlBlocked($contact['url'])) {
482 $profile = APContact::getByURL($contact['url'], false);
483 if (!empty($profile)) {
484 if (empty($profile['sharedinbox']) || $personal) {
485 $target = $profile['inbox'];
487 $target = $profile['sharedinbox'];
489 $inboxes[$target] = $target;
492 DBA::close($contacts);
498 * Fetches an array of inboxes for the given item and user
501 * @param integer $uid User ID
502 * @param boolean $personal fetch personal inboxes
503 * @param integer $last_id Last item id for adding receivers
505 * @return array with inboxes
506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
507 * @throws \ImagickException
509 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
511 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
512 if (empty($permissions)) {
518 if ($item['gravity'] == GRAVITY_ACTIVITY) {
519 $item_profile = APContact::getByURL($item['author-link'], false);
521 $item_profile = APContact::getByURL($item['owner-link'], false);
524 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
525 if (empty($permissions[$element])) {
529 $blindcopy = in_array($element, ['bto', 'bcc']);
531 foreach ($permissions[$element] as $receiver) {
532 if (Network::isUrlBlocked($receiver)) {
536 if ($receiver == $item_profile['followers']) {
537 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
539 $profile = APContact::getByURL($receiver, false);
540 if (!empty($profile)) {
541 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
542 $target = $profile['inbox'];
544 $target = $profile['sharedinbox'];
546 $inboxes[$target] = $target;
556 * Returns the activity type of a given item
560 * @return string with activity type
561 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
562 * @throws \ImagickException
564 private static function getTypeOfItem($item)
568 // Only check for a reshare, if it is a real reshare and no quoted reshare
569 if (strpos($item['body'], "[share") === 0) {
570 $announce = api_share_as_retweet($item);
571 $reshared = !empty($announce['plink']);
576 } elseif ($item['verb'] == ACTIVITY_POST) {
577 if ($item['created'] == $item['edited']) {
582 } elseif ($item['verb'] == ACTIVITY_LIKE) {
584 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
586 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
588 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
590 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
591 $type = 'TentativeAccept';
600 * Creates the activity or fetches it from the cache
602 * @param integer $item_id
603 * @param boolean $force Force new cache entry
605 * @return array with the activity
608 public static function createCachedActivityFromItem($item_id, $force = false)
610 $cachekey = 'APDelivery:createActivity:' . $item_id;
613 $data = Cache::get($cachekey);
614 if (!is_null($data)) {
619 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
621 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
626 * Creates an activity array for a given item id
628 * @param integer $item_id
629 * @param boolean $object_mode Is the activity item is used inside another object?
631 * @return array of activity
634 public static function createActivityFromItem($item_id, $object_mode = false)
636 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
638 if (!DBA::isResult($item)) {
642 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
643 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
644 if (DBA::isResult($conversation)) {
645 $data = json_decode($conversation['source']);
651 $type = self::getTypeOfItem($item);
654 $data = ['@context' => ActivityPub::CONTEXT];
656 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
658 } elseif ($item['deleted']) {
665 $data['id'] = $item['uri'] . '#' . $type;
666 $data['type'] = $type;
667 $data['actor'] = $item['owner-link'];
669 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
671 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
673 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
675 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
676 $data['object'] = self::createNote($item);
677 } elseif ($data['type'] == 'Announce') {
678 $data['object'] = self::createAnnounce($item);
679 } elseif ($data['type'] == 'Undo') {
680 $data['object'] = self::createActivityFromItem($item_id, true);
682 $data['diaspora:guid'] = $item['guid'];
683 if (!empty($item['signed_text'])) {
684 $data['diaspora:like'] = $item['signed_text'];
686 $data['object'] = $item['thr-parent'];
689 if (!empty($item['contact-uid'])) {
690 $uid = $item['contact-uid'];
695 $owner = User::getOwnerDataById($uid);
697 if (!$object_mode && !empty($owner)) {
698 return LDSignature::sign($data, $owner);
703 /// @todo Create "conversation" entry
707 * Creates an object array for a given item id
709 * @param integer $item_id
711 * @return array with the object data
712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
713 * @throws \ImagickException
715 public static function createObjectFromItemID($item_id)
717 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
719 if (!DBA::isResult($item)) {
723 $data = ['@context' => ActivityPub::CONTEXT];
724 $data = array_merge($data, self::createNote($item));
730 * Creates a location entry for a given item array
734 * @return array with location array
736 private static function createLocation($item)
738 $location = ['type' => 'Place'];
740 if (!empty($item['location'])) {
741 $location['name'] = $item['location'];
746 if (empty($item['coord'])) {
747 $coord = Map::getCoordinates($item['location']);
749 $coords = explode(' ', $item['coord']);
750 if (count($coords) == 2) {
751 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
755 if (!empty($coord['lat']) && !empty($coord['lon'])) {
756 $location['latitude'] = $coord['lat'];
757 $location['longitude'] = $coord['lon'];
764 * Returns a tag array for a given item array
768 * @return array of tags
769 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
771 private static function createTagList($item)
775 $terms = Term::tagArrayFromItemId($item['id']);
776 foreach ($terms as $term) {
777 if ($term['type'] == TERM_HASHTAG) {
778 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
779 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
780 } elseif ($term['type'] == TERM_MENTION) {
781 $contact = Contact::getDetailsByURL($term['url']);
782 if (!empty($contact['addr'])) {
783 $mention = '@' . $contact['addr'];
785 $mention = '@' . $term['url'];
788 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
795 * Adds attachment data to the JSON document
797 * @param array $item Data of the item that is to be posted
798 * @param string $type Object type
800 * @return array with attachment data
801 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
803 private static function createAttachmentList($item, $type)
807 $arr = explode('[/attach],', $item['attach']);
809 foreach ($arr as $r) {
811 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
813 $attributes = ['type' => 'Document',
814 'mediaType' => $matches[3],
815 'url' => $matches[1],
818 if (trim($matches[4]) != '') {
819 $attributes['name'] = trim($matches[4]);
822 $attachments[] = $attributes;
827 if ($type != 'Note') {
831 // Simplify image codes
832 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
834 // Grab all pictures and create attachments out of them
835 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
836 foreach ($pictures[1] as $picture) {
837 $imgdata = Image::getInfoFromURL($picture);
839 $attachments[] = ['type' => 'Document',
840 'mediaType' => $imgdata['mime'],
851 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
853 * @param array $match Matching values for the callback
854 * @return string Replaced mention
855 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
857 private static function mentionCallback($match)
859 if (empty($match[1])) {
863 $data = Contact::getDetailsByURL($match[1]);
864 if (empty($data) || empty($data['nick'])) {
868 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
872 * Remove image elements and replaces them with links to the image
874 * @param string $body
876 * @return string with replaced elements
878 private static function removePictures($body)
880 // Simplify image codes
881 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
883 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
884 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
890 * Fetches the "context" value for a givem item array from the "conversation" table
894 * @return string with context url
897 private static function fetchContextURLForItem($item)
899 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
900 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
901 $context_uri = $conversation['conversation-href'];
902 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
903 $context_uri = $conversation['conversation-uri'];
905 $context_uri = $item['parent-uri'] . '#context';
911 * Returns if the post contains sensitive content ("nsfw")
913 * @param integer $item_id
918 private static function isSensitive($item_id)
920 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
921 return DBA::exists('term', $condition);
929 * @return array with the event data
930 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
932 public static function createEvent($item)
935 $event['name'] = $item['event-summary'];
936 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
937 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
939 if (!$item['event-nofinish']) {
940 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
943 if (!empty($item['event-location'])) {
944 $item['location'] = $item['event-location'];
945 $event['location'] = self::createLocation($item);
952 * Creates a note/article object array
956 * @return array with the object data
957 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
958 * @throws \ImagickException
960 public static function createNote($item)
962 if ($item['event-type'] == 'event') {
964 } elseif (!empty($item['title'])) {
970 if ($item['deleted']) {
975 $data['id'] = $item['uri'];
976 $data['type'] = $type;
978 if ($item['deleted']) {
982 $data['summary'] = null; // Ignore by now
984 if ($item['uri'] != $item['thr-parent']) {
985 $data['inReplyTo'] = $item['thr-parent'];
987 $data['inReplyTo'] = null;
990 $data['diaspora:guid'] = $item['guid'];
991 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
993 if ($item['created'] != $item['edited']) {
994 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
997 $data['url'] = $item['plink'];
998 $data['attributedTo'] = $item['author-link'];
999 $data['sensitive'] = self::isSensitive($item['id']);
1000 $data['context'] = self::fetchContextURLForItem($item);
1002 if (!empty($item['title'])) {
1003 $data['name'] = BBCode::toPlaintext($item['title'], false);
1006 $body = $item['body'];
1008 if ($type == 'Note') {
1009 $body = self::removePictures($body);
1012 if ($type == 'Event') {
1013 $data = array_merge($data, self::createEvent($item));
1015 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1016 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1018 $data['content'] = BBCode::convert($body, false, 7);
1021 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1023 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1024 $data['diaspora:comment'] = $item['signed_text'];
1027 $data['attachment'] = self::createAttachmentList($item, $type);
1028 $data['tag'] = self::createTagList($item);
1030 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1031 $data['location'] = self::createLocation($item);
1034 if (!empty($item['app'])) {
1035 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1038 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1044 * Creates an announce object entry
1046 * @param array $item
1048 * @return string with announced object url
1049 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1050 * @throws \ImagickException
1052 public static function createAnnounce($item)
1054 $announce = api_share_as_retweet($item);
1055 if (empty($announce['plink'])) {
1056 return self::createNote($item);
1059 // Fetch the original id of the object
1060 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1061 if (!empty($activity)) {
1062 $ldactivity = JsonLD::compact($activity);
1063 $id = JsonLD::fetchElement($ldactivity, '@id');
1069 return self::createNote($item);
1073 * Creates an activity id for a given contact id
1075 * @param integer $cid Contact ID of target
1077 * @return bool|string activity id
1079 public static function activityIDFromContact($cid)
1081 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1082 if (!DBA::isResult($contact)) {
1086 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1087 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1088 return System::baseUrl() . '/activity/' . $uuid;
1092 * Transmits a contact suggestion to a given inbox
1094 * @param integer $uid User ID
1095 * @param string $inbox Target inbox
1096 * @param integer $suggestion_id Suggestion ID
1098 * @return boolean was the transmission successful?
1099 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1101 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1103 $owner = User::getOwnerDataById($uid);
1105 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1107 $data = ['@context' => ActivityPub::CONTEXT,
1108 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1109 'type' => 'Announce',
1110 'actor' => $owner['url'],
1111 'object' => $suggestion['url'],
1112 'content' => $suggestion['note'],
1113 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1114 'to' => [ActivityPub::PUBLIC_COLLECTION],
1117 $signed = LDSignature::sign($data, $owner);
1119 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1120 return HTTPSignature::transmit($signed, $inbox, $uid);
1124 * Transmits a profile relocation to a given inbox
1126 * @param integer $uid User ID
1127 * @param string $inbox Target inbox
1129 * @return boolean was the transmission successful?
1130 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1132 public static function sendProfileRelocation($uid, $inbox)
1134 $owner = User::getOwnerDataById($uid);
1136 $data = ['@context' => ActivityPub::CONTEXT,
1137 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1138 'type' => 'dfrn:relocate',
1139 'actor' => $owner['url'],
1140 'object' => $owner['url'],
1141 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1142 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1143 'to' => [ActivityPub::PUBLIC_COLLECTION],
1146 $signed = LDSignature::sign($data, $owner);
1148 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1149 return HTTPSignature::transmit($signed, $inbox, $uid);
1153 * Transmits a profile deletion to a given inbox
1155 * @param integer $uid User ID
1156 * @param string $inbox Target inbox
1158 * @return boolean was the transmission successful?
1159 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1161 public static function sendProfileDeletion($uid, $inbox)
1163 $owner = User::getOwnerDataById($uid);
1165 $data = ['@context' => ActivityPub::CONTEXT,
1166 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1168 'actor' => $owner['url'],
1169 'object' => $owner['url'],
1170 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1171 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1172 'to' => [ActivityPub::PUBLIC_COLLECTION],
1175 $signed = LDSignature::sign($data, $owner);
1177 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1178 return HTTPSignature::transmit($signed, $inbox, $uid);
1182 * Transmits a profile change to a given inbox
1184 * @param integer $uid User ID
1185 * @param string $inbox Target inbox
1187 * @return boolean was the transmission successful?
1188 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1189 * @throws \ImagickException
1191 public static function sendProfileUpdate($uid, $inbox)
1193 $owner = User::getOwnerDataById($uid);
1194 $profile = APContact::getByURL($owner['url']);
1196 $data = ['@context' => ActivityPub::CONTEXT,
1197 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1199 'actor' => $owner['url'],
1200 'object' => self::getProfile($uid),
1201 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1202 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1203 'to' => [$profile['followers']],
1206 $signed = LDSignature::sign($data, $owner);
1208 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1209 return HTTPSignature::transmit($signed, $inbox, $uid);
1213 * Transmits a given activity to a target
1215 * @param array $activity
1216 * @param string $target Target profile
1217 * @param integer $uid User ID
1218 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1219 * @throws \ImagickException
1220 * @throws \Exception
1222 public static function sendActivity($activity, $target, $uid, $id = '')
1224 $profile = APContact::getByURL($target);
1226 $owner = User::getOwnerDataById($uid);
1229 $id = System::baseUrl() . '/activity/' . System::createGUID();
1232 $data = ['@context' => ActivityPub::CONTEXT,
1234 'type' => $activity,
1235 'actor' => $owner['url'],
1236 'object' => $profile['url'],
1237 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1238 'to' => [$profile['url']]];
1240 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1242 $signed = LDSignature::sign($data, $owner);
1243 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1247 * Transmit a message that the contact request had been accepted
1249 * @param string $target Target profile
1251 * @param integer $uid User ID
1252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1253 * @throws \ImagickException
1255 public static function sendContactAccept($target, $id, $uid)
1257 $profile = APContact::getByURL($target);
1259 $owner = User::getOwnerDataById($uid);
1260 $data = ['@context' => ActivityPub::CONTEXT,
1261 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1263 'actor' => $owner['url'],
1264 'object' => ['id' => $id, 'type' => 'Follow',
1265 'actor' => $profile['url'],
1266 'object' => $owner['url']],
1267 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1268 'to' => [$profile['url']]];
1270 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1272 $signed = LDSignature::sign($data, $owner);
1273 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1277 * Reject a contact request or terminates the contact relation
1279 * @param string $target Target profile
1281 * @param integer $uid User ID
1282 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1283 * @throws \ImagickException
1285 public static function sendContactReject($target, $id, $uid)
1287 $profile = APContact::getByURL($target);
1289 $owner = User::getOwnerDataById($uid);
1290 $data = ['@context' => ActivityPub::CONTEXT,
1291 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1293 'actor' => $owner['url'],
1294 'object' => ['id' => $id, 'type' => 'Follow',
1295 'actor' => $profile['url'],
1296 'object' => $owner['url']],
1297 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1298 'to' => [$profile['url']]];
1300 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1302 $signed = LDSignature::sign($data, $owner);
1303 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1307 * Transmits a message that we don't want to follow this contact anymore
1309 * @param string $target Target profile
1310 * @param integer $uid User ID
1311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1312 * @throws \ImagickException
1313 * @throws \Exception
1315 public static function sendContactUndo($target, $cid, $uid)
1317 $profile = APContact::getByURL($target);
1319 $object_id = self::activityIDFromContact($cid);
1320 if (empty($object_id)) {
1324 $id = System::baseUrl() . '/activity/' . System::createGUID();
1326 $owner = User::getOwnerDataById($uid);
1327 $data = ['@context' => ActivityPub::CONTEXT,
1330 'actor' => $owner['url'],
1331 'object' => ['id' => $object_id, 'type' => 'Follow',
1332 'actor' => $owner['url'],
1333 'object' => $profile['url']],
1334 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1335 'to' => [$profile['url']]];
1337 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1339 $signed = LDSignature::sign($data, $owner);
1340 HTTPSignature::transmit($signed, $profile['inbox'], $uid);