3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Core\Logger;
10 use Friendica\Core\System;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\APContact;
16 use Friendica\Model\Item;
17 use Friendica\Model\Term;
18 use Friendica\Model\User;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Util\JsonLD;
22 use Friendica\Util\LDSignature;
23 use Friendica\Model\Profile;
24 use Friendica\Object\Image;
25 use Friendica\Protocol\ActivityPub;
26 use Friendica\Protocol\Diaspora;
27 use Friendica\Core\Cache;
28 use Friendica\Util\Map;
29 use Friendica\Util\Network;
31 require_once 'include/api.php';
34 * @brief ActivityPub Transmitter Protocol class
42 * collects the lost of followers of the given owner
44 * @param array $owner Owner array
45 * @param integer $page Page number
47 * @return array of owners
48 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
50 public static function getFollowers($owner, $page = null)
52 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
53 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
54 $count = DBA::count('contact', $condition);
56 $data = ['@context' => ActivityPub::CONTEXT];
57 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
58 $data['type'] = 'OrderedCollection';
59 $data['totalItems'] = $count;
61 // When we hide our friends we will only show the pure number but don't allow more.
62 $profile = Profile::getByUID($owner['uid']);
63 if (!empty($profile['hide-friends'])) {
68 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
72 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
73 while ($contact = DBA::fetch($contacts)) {
74 $list[] = $contact['url'];
78 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
81 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
83 $data['orderedItems'] = $list;
90 * Create list of following contacts
92 * @param array $owner Owner array
93 * @param integer $page Page numbe
95 * @return array of following contacts
96 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
98 public static function getFollowing($owner, $page = null)
100 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
101 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
102 $count = DBA::count('contact', $condition);
104 $data = ['@context' => ActivityPub::CONTEXT];
105 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
106 $data['type'] = 'OrderedCollection';
107 $data['totalItems'] = $count;
109 // When we hide our friends we will only show the pure number but don't allow more.
110 $profile = Profile::getByUID($owner['uid']);
111 if (!empty($profile['hide-friends'])) {
116 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
120 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
121 while ($contact = DBA::fetch($contacts)) {
122 $list[] = $contact['url'];
126 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
129 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
131 $data['orderedItems'] = $list;
138 * Public posts for the given owner
140 * @param array $owner Owner array
141 * @param integer $page Page numbe
143 * @return array of posts
144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
145 * @throws \ImagickException
147 public static function getOutbox($owner, $page = null)
149 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
151 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
152 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
153 'deleted' => false, 'visible' => true];
154 $count = DBA::count('item', $condition);
156 $data = ['@context' => ActivityPub::CONTEXT];
157 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
158 $data['type'] = 'OrderedCollection';
159 $data['totalItems'] = $count;
162 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
166 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
168 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
169 while ($item = Item::fetch($items)) {
170 $object = self::createObjectFromItemID($item['id']);
171 unset($object['@context']);
176 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
179 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
181 $data['orderedItems'] = $list;
188 * Return the ActivityPub profile of the given user
190 * @param integer $uid User ID
191 * @return array with profile data
192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
194 public static function getProfile($uid)
196 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
197 'account_removed' => false, 'verified' => true];
198 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
199 $user = DBA::selectFirst('user', $fields, $condition);
200 if (!DBA::isResult($user)) {
204 $fields = ['locality', 'region', 'country-name'];
205 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
206 if (!DBA::isResult($profile)) {
210 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
211 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
212 if (!DBA::isResult($contact)) {
216 // On old installations and never changed contacts this might not be filled
217 if (empty($contact['avatar'])) {
218 $contact['avatar'] = $contact['photo'];
221 $data = ['@context' => ActivityPub::CONTEXT];
222 $data['id'] = $contact['url'];
223 $data['diaspora:guid'] = $user['guid'];
224 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
225 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
226 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
227 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
228 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
229 $data['preferredUsername'] = $user['nickname'];
230 $data['name'] = $contact['name'];
231 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
232 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
233 $data['summary'] = $contact['about'];
234 $data['url'] = $contact['url'];
235 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
236 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
237 'owner' => $contact['url'],
238 'publicKeyPem' => $user['pubkey']];
239 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
240 $data['icon'] = ['type' => 'Image',
241 'url' => $contact['avatar']];
243 // tags: https://kitty.town/@inmysocks/100656097926961126.json
248 * Returns an array with permissions of a given item array
252 * @return array with permissions
253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
254 * @throws \ImagickException
256 private static function fetchPermissionBlockFromConversation($item)
258 if (empty($item['thr-parent'])) {
262 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
263 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
264 if (!DBA::isResult($conversation)) {
268 $activity = json_decode($conversation['source'], true);
270 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
271 $profile = APContact::getByURL($actor);
273 $item_profile = APContact::getByURL($item['author-link']);
274 $exclude[] = $item['author-link'];
276 if ($item['gravity'] == GRAVITY_PARENT) {
277 $exclude[] = $item['owner-link'];
280 $permissions['to'][] = $actor;
282 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
283 if (empty($activity[$element])) {
286 if (is_string($activity[$element])) {
287 $activity[$element] = [$activity[$element]];
290 foreach ($activity[$element] as $receiver) {
291 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
292 $permissions[$element][] = $item_profile['followers'];
293 } elseif (!in_array($receiver, $exclude)) {
294 $permissions[$element][] = $receiver;
302 * Creates an array of permissions from an item thread
305 * @param boolean $blindcopy
306 * @param boolean $last_id
308 * @return array with permission data
309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
310 * @throws \ImagickException
312 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
315 $last_id = $item['id'];
320 // Check if we should always deliver our stuff via BCC
321 if (!empty($item['uid'])) {
322 $profile = Profile::getByUID($item['uid']);
323 if (!empty($profile)) {
324 $always_bcc = $profile['hide-friends'];
328 // Will be activated in a later step
329 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
331 // For now only send to these contacts:
332 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
334 $data = ['to' => [], 'cc' => [], 'bcc' => []];
336 $actor_profile = APContact::getByURL($item['author-link']);
338 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
340 if (!$item['private']) {
341 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
343 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
344 if (!empty($actor_profile['followers'])) {
345 $data['cc'][] = $actor_profile['followers'];
348 foreach ($terms as $term) {
349 $profile = APContact::getByURL($term['url'], false);
350 if (!empty($profile)) {
351 $data['to'][] = $profile['url'];
355 $receiver_list = Item::enumeratePermissions($item);
357 foreach ($terms as $term) {
358 $cid = Contact::getIdForURL($term['url'], $item['uid']);
359 if (!empty($cid) && in_array($cid, $receiver_list)) {
360 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
361 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
362 $data['to'][] = $profile['url'];
367 foreach ($receiver_list as $receiver) {
368 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
369 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
370 if ($contact['hidden'] || $always_bcc) {
371 $data['bcc'][] = $profile['url'];
373 $data['cc'][] = $profile['url'];
379 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
380 while ($parent = Item::fetch($parents)) {
381 // Don't include data from future posts
382 if ($parent['id'] >= $last_id) {
386 $profile = APContact::getByURL($parent['author-link'], false);
387 if (!empty($profile)) {
388 if ($parent['uri'] == $item['thr-parent']) {
389 $data['to'][] = $profile['url'];
391 $data['cc'][] = $profile['url'];
395 if ($item['gravity'] != GRAVITY_PARENT) {
399 $profile = APContact::getByURL($parent['owner-link'], false);
400 if (!empty($profile)) {
401 $data['cc'][] = $profile['url'];
404 DBA::close($parents);
406 $data['to'] = array_unique($data['to']);
407 $data['cc'] = array_unique($data['cc']);
408 $data['bcc'] = array_unique($data['bcc']);
410 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
411 unset($data['to'][$key]);
414 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
415 unset($data['cc'][$key]);
418 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
419 unset($data['bcc'][$key]);
422 foreach ($data['to'] as $to) {
423 if (($key = array_search($to, $data['cc'])) !== false) {
424 unset($data['cc'][$key]);
427 if (($key = array_search($to, $data['bcc'])) !== false) {
428 unset($data['bcc'][$key]);
432 foreach ($data['cc'] as $cc) {
433 if (($key = array_search($cc, $data['bcc'])) !== false) {
434 unset($data['bcc'][$key]);
438 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
441 unset($receivers['bcc']);
448 * Fetches a list of inboxes of followers of a given user
450 * @param integer $uid User ID
451 * @param boolean $personal fetch personal inboxes
453 * @return array of follower inboxes
454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
455 * @throws \ImagickException
457 public static function fetchTargetInboxesforUser($uid, $personal = false)
461 // Will be activated in a later step
462 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
464 // For now only send to these contacts:
465 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
467 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
470 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
473 $contacts = DBA::select('contact', ['url'], $condition);
474 while ($contact = DBA::fetch($contacts)) {
475 if (Network::isUrlBlocked($contact['url'])) {
479 $profile = APContact::getByURL($contact['url'], false);
480 if (!empty($profile)) {
481 if (empty($profile['sharedinbox']) || $personal) {
482 $target = $profile['inbox'];
484 $target = $profile['sharedinbox'];
486 $inboxes[$target] = $target;
489 DBA::close($contacts);
495 * Fetches an array of inboxes for the given item and user
498 * @param integer $uid User ID
499 * @param boolean $personal fetch personal inboxes
500 * @param integer $last_id Last item id for adding receivers
502 * @return array with inboxes
503 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
504 * @throws \ImagickException
506 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
508 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
509 if (empty($permissions)) {
515 if ($item['gravity'] == GRAVITY_ACTIVITY) {
516 $item_profile = APContact::getByURL($item['author-link'], false);
518 $item_profile = APContact::getByURL($item['owner-link'], false);
521 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
522 if (empty($permissions[$element])) {
526 $blindcopy = in_array($element, ['bto', 'bcc']);
528 foreach ($permissions[$element] as $receiver) {
529 if (Network::isUrlBlocked($receiver)) {
533 if ($receiver == $item_profile['followers']) {
534 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
536 $profile = APContact::getByURL($receiver, false);
537 if (!empty($profile)) {
538 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
539 $target = $profile['inbox'];
541 $target = $profile['sharedinbox'];
543 $inboxes[$target] = $target;
553 * Returns the activity type of a given item
557 * @return string with activity type
558 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
559 * @throws \ImagickException
561 private static function getTypeOfItem($item)
565 // Only check for a reshare, if it is a real reshare and no quoted reshare
566 if (strpos($item['body'], "[share") === 0) {
567 $announce = api_share_as_retweet($item);
568 $reshared = !empty($announce['plink']);
573 } elseif ($item['verb'] == ACTIVITY_POST) {
574 if ($item['created'] == $item['edited']) {
579 } elseif ($item['verb'] == ACTIVITY_LIKE) {
581 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
583 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
585 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
587 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
588 $type = 'TentativeAccept';
597 * Creates the activity or fetches it from the cache
599 * @param integer $item_id
600 * @param boolean $force Force new cache entry
602 * @return array with the activity
605 public static function createCachedActivityFromItem($item_id, $force = false)
607 $cachekey = 'APDelivery:createActivity:' . $item_id;
610 $data = Cache::get($cachekey);
611 if (!is_null($data)) {
616 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
618 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
623 * Creates an activity array for a given item id
625 * @param integer $item_id
626 * @param boolean $object_mode Is the activity item is used inside another object?
628 * @return array of activity
631 public static function createActivityFromItem($item_id, $object_mode = false)
633 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
635 if (!DBA::isResult($item)) {
639 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
640 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
641 if (DBA::isResult($conversation)) {
642 $data = json_decode($conversation['source']);
648 $type = self::getTypeOfItem($item);
651 $data = ['@context' => ActivityPub::CONTEXT];
653 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
655 } elseif ($item['deleted']) {
662 $data['id'] = $item['uri'] . '#' . $type;
663 $data['type'] = $type;
664 $data['actor'] = $item['owner-link'];
666 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
668 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
670 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
672 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
673 $data['object'] = self::createNote($item);
674 } elseif ($data['type'] == 'Announce') {
675 $data['object'] = self::createAnnounce($item);
676 } elseif ($data['type'] == 'Undo') {
677 $data['object'] = self::createActivityFromItem($item_id, true);
679 $data['diaspora:guid'] = $item['guid'];
680 if (!empty($item['signed_text'])) {
681 $data['diaspora:like'] = $item['signed_text'];
683 $data['object'] = $item['thr-parent'];
686 if (!empty($item['contact-uid'])) {
687 $uid = $item['contact-uid'];
692 $owner = User::getOwnerDataById($uid);
694 if (!$object_mode && !empty($owner)) {
695 return LDSignature::sign($data, $owner);
700 /// @todo Create "conversation" entry
704 * Creates an object array for a given item id
706 * @param integer $item_id
708 * @return array with the object data
709 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
710 * @throws \ImagickException
712 public static function createObjectFromItemID($item_id)
714 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
716 if (!DBA::isResult($item)) {
720 $data = ['@context' => ActivityPub::CONTEXT];
721 $data = array_merge($data, self::createNote($item));
727 * Creates a location entry for a given item array
731 * @return array with location array
733 private static function createLocation($item)
735 $location = ['type' => 'Place'];
737 if (!empty($item['location'])) {
738 $location['name'] = $item['location'];
743 if (empty($item['coord'])) {
744 $coord = Map::getCoordinates($item['location']);
746 $coords = explode(' ', $item['coord']);
747 if (count($coords) == 2) {
748 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
752 if (!empty($coord['lat']) && !empty($coord['lon'])) {
753 $location['latitude'] = $coord['lat'];
754 $location['longitude'] = $coord['lon'];
761 * Returns a tag array for a given item array
765 * @return array of tags
766 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
768 private static function createTagList($item)
772 $terms = Term::tagArrayFromItemId($item['id']);
773 foreach ($terms as $term) {
774 if ($term['type'] == TERM_HASHTAG) {
775 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
776 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
777 } elseif ($term['type'] == TERM_MENTION) {
778 $contact = Contact::getDetailsByURL($term['url']);
779 if (!empty($contact['addr'])) {
780 $mention = '@' . $contact['addr'];
782 $mention = '@' . $term['url'];
785 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
792 * Adds attachment data to the JSON document
794 * @param array $item Data of the item that is to be posted
795 * @param string $type Object type
797 * @return array with attachment data
798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
800 private static function createAttachmentList($item, $type)
804 $arr = explode('[/attach],', $item['attach']);
806 foreach ($arr as $r) {
808 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
810 $attributes = ['type' => 'Document',
811 'mediaType' => $matches[3],
812 'url' => $matches[1],
815 if (trim($matches[4]) != '') {
816 $attributes['name'] = trim($matches[4]);
819 $attachments[] = $attributes;
824 if ($type != 'Note') {
828 // Simplify image codes
829 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
831 // Grab all pictures and create attachments out of them
832 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
833 foreach ($pictures[1] as $picture) {
834 $imgdata = Image::getInfoFromURL($picture);
836 $attachments[] = ['type' => 'Document',
837 'mediaType' => $imgdata['mime'],
848 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
850 * @param array $match Matching values for the callback
851 * @return string Replaced mention
852 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
854 private static function mentionCallback($match)
856 if (empty($match[1])) {
860 $data = Contact::getDetailsByURL($match[1]);
861 if (empty($data) || empty($data['nick'])) {
865 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
869 * Remove image elements and replaces them with links to the image
871 * @param string $body
873 * @return string with replaced elements
875 private static function removePictures($body)
877 // Simplify image codes
878 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
880 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
881 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
887 * Fetches the "context" value for a givem item array from the "conversation" table
891 * @return string with context url
894 private static function fetchContextURLForItem($item)
896 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
897 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
898 $context_uri = $conversation['conversation-href'];
899 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
900 $context_uri = $conversation['conversation-uri'];
902 $context_uri = $item['parent-uri'] . '#context';
908 * Returns if the post contains sensitive content ("nsfw")
910 * @param integer $item_id
915 private static function isSensitive($item_id)
917 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
918 return DBA::exists('term', $condition);
926 * @return array with the event data
927 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
929 public static function createEvent($item)
932 $event['name'] = $item['event-summary'];
933 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
934 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
936 if (!$item['event-nofinish']) {
937 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
940 if (!empty($item['event-location'])) {
941 $item['location'] = $item['event-location'];
942 $event['location'] = self::createLocation($item);
949 * Creates a note/article object array
953 * @return array with the object data
954 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
955 * @throws \ImagickException
957 public static function createNote($item)
959 if ($item['event-type'] == 'event') {
961 } elseif (!empty($item['title'])) {
967 if ($item['deleted']) {
972 $data['id'] = $item['uri'];
973 $data['type'] = $type;
975 if ($item['deleted']) {
979 $data['summary'] = null; // Ignore by now
981 if ($item['uri'] != $item['thr-parent']) {
982 $data['inReplyTo'] = $item['thr-parent'];
984 $data['inReplyTo'] = null;
987 $data['diaspora:guid'] = $item['guid'];
988 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
990 if ($item['created'] != $item['edited']) {
991 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
994 $data['url'] = $item['plink'];
995 $data['attributedTo'] = $item['author-link'];
996 $data['sensitive'] = self::isSensitive($item['id']);
997 $data['context'] = self::fetchContextURLForItem($item);
999 if (!empty($item['title'])) {
1000 $data['name'] = BBCode::toPlaintext($item['title'], false);
1003 $body = $item['body'];
1005 if ($type == 'Note') {
1006 $body = self::removePictures($body);
1009 if ($type == 'Event') {
1010 $data = array_merge($data, self::createEvent($item));
1012 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1013 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1015 $data['content'] = BBCode::convert($body, false, 7);
1018 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1020 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1021 $data['diaspora:comment'] = $item['signed_text'];
1024 $data['attachment'] = self::createAttachmentList($item, $type);
1025 $data['tag'] = self::createTagList($item);
1027 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1028 $data['location'] = self::createLocation($item);
1031 if (!empty($item['app'])) {
1032 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1035 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1041 * Creates an announce object entry
1043 * @param array $item
1045 * @return string with announced object url
1046 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1047 * @throws \ImagickException
1049 public static function createAnnounce($item)
1051 $announce = api_share_as_retweet($item);
1052 if (empty($announce['plink'])) {
1053 return self::createNote($item);
1056 // Fetch the original id of the object
1057 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1058 if (!empty($activity)) {
1059 $ldactivity = JsonLD::compact($activity);
1060 $id = JsonLD::fetchElement($ldactivity, '@id');
1066 return self::createNote($item);
1070 * Creates an activity id for a given contact id
1072 * @param integer $cid Contact ID of target
1074 * @return bool|string activity id
1076 public static function activityIDFromContact($cid)
1078 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1079 if (!DBA::isResult($contact)) {
1083 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1084 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1085 return System::baseUrl() . '/activity/' . $uuid;
1089 * Transmits a contact suggestion to a given inbox
1091 * @param integer $uid User ID
1092 * @param string $inbox Target inbox
1093 * @param integer $suggestion_id Suggestion ID
1095 * @return boolean was the transmission successful?
1096 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1098 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1100 $owner = User::getOwnerDataById($uid);
1102 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1104 $data = ['@context' => ActivityPub::CONTEXT,
1105 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1106 'type' => 'Announce',
1107 'actor' => $owner['url'],
1108 'object' => $suggestion['url'],
1109 'content' => $suggestion['note'],
1110 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1111 'to' => [ActivityPub::PUBLIC_COLLECTION],
1114 $signed = LDSignature::sign($data, $owner);
1116 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1117 return HTTPSignature::transmit($signed, $inbox, $uid);
1121 * Transmits a profile relocation to a given inbox
1123 * @param integer $uid User ID
1124 * @param string $inbox Target inbox
1126 * @return boolean was the transmission successful?
1127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1129 public static function sendProfileRelocation($uid, $inbox)
1131 $owner = User::getOwnerDataById($uid);
1133 $data = ['@context' => ActivityPub::CONTEXT,
1134 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1135 'type' => 'dfrn:relocate',
1136 'actor' => $owner['url'],
1137 'object' => $owner['url'],
1138 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1139 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1140 'to' => [ActivityPub::PUBLIC_COLLECTION],
1143 $signed = LDSignature::sign($data, $owner);
1145 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1146 return HTTPSignature::transmit($signed, $inbox, $uid);
1150 * Transmits a profile deletion to a given inbox
1152 * @param integer $uid User ID
1153 * @param string $inbox Target inbox
1155 * @return boolean was the transmission successful?
1156 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1158 public static function sendProfileDeletion($uid, $inbox)
1160 $owner = User::getOwnerDataById($uid);
1162 $data = ['@context' => ActivityPub::CONTEXT,
1163 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1165 'actor' => $owner['url'],
1166 'object' => $owner['url'],
1167 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1168 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1169 'to' => [ActivityPub::PUBLIC_COLLECTION],
1172 $signed = LDSignature::sign($data, $owner);
1174 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1175 return HTTPSignature::transmit($signed, $inbox, $uid);
1179 * Transmits a profile change to a given inbox
1181 * @param integer $uid User ID
1182 * @param string $inbox Target inbox
1184 * @return boolean was the transmission successful?
1185 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1186 * @throws \ImagickException
1188 public static function sendProfileUpdate($uid, $inbox)
1190 $owner = User::getOwnerDataById($uid);
1191 $profile = APContact::getByURL($owner['url']);
1193 $data = ['@context' => ActivityPub::CONTEXT,
1194 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1196 'actor' => $owner['url'],
1197 'object' => self::getProfile($uid),
1198 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1199 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1200 'to' => [$profile['followers']],
1203 $signed = LDSignature::sign($data, $owner);
1205 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1206 return HTTPSignature::transmit($signed, $inbox, $uid);
1210 * Transmits a given activity to a target
1212 * @param string $activity Type name
1213 * @param string $target Target profile
1214 * @param integer $uid User ID
1216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1217 * @throws \ImagickException
1218 * @throws \Exception
1220 public static function sendActivity($activity, $target, $uid, $id = '')
1222 $profile = APContact::getByURL($target);
1224 $owner = User::getOwnerDataById($uid);
1227 $id = System::baseUrl() . '/activity/' . System::createGUID();
1230 $data = ['@context' => ActivityPub::CONTEXT,
1232 'type' => $activity,
1233 'actor' => $owner['url'],
1234 'object' => $profile['url'],
1235 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1236 'to' => [$profile['url']]];
1238 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1240 $signed = LDSignature::sign($data, $owner);
1241 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1245 * Transmit a message that the contact request had been accepted
1247 * @param string $target Target profile
1249 * @param integer $uid User ID
1250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1251 * @throws \ImagickException
1253 public static function sendContactAccept($target, $id, $uid)
1255 $profile = APContact::getByURL($target);
1257 $owner = User::getOwnerDataById($uid);
1258 $data = ['@context' => ActivityPub::CONTEXT,
1259 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1261 'actor' => $owner['url'],
1262 'object' => ['id' => $id, 'type' => 'Follow',
1263 'actor' => $profile['url'],
1264 'object' => $owner['url']],
1265 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1266 'to' => [$profile['url']]];
1268 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1270 $signed = LDSignature::sign($data, $owner);
1271 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1275 * Reject a contact request or terminates the contact relation
1277 * @param string $target Target profile
1279 * @param integer $uid User ID
1280 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1281 * @throws \ImagickException
1283 public static function sendContactReject($target, $id, $uid)
1285 $profile = APContact::getByURL($target);
1287 $owner = User::getOwnerDataById($uid);
1288 $data = ['@context' => ActivityPub::CONTEXT,
1289 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1291 'actor' => $owner['url'],
1292 'object' => ['id' => $id, 'type' => 'Follow',
1293 'actor' => $profile['url'],
1294 'object' => $owner['url']],
1295 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1296 'to' => [$profile['url']]];
1298 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1300 $signed = LDSignature::sign($data, $owner);
1301 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1305 * Transmits a message that we don't want to follow this contact anymore
1307 * @param string $target Target profile
1308 * @param integer $uid User ID
1309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1310 * @throws \ImagickException
1311 * @throws \Exception
1313 public static function sendContactUndo($target, $cid, $uid)
1315 $profile = APContact::getByURL($target);
1317 $object_id = self::activityIDFromContact($cid);
1318 if (empty($object_id)) {
1322 $id = System::baseUrl() . '/activity/' . System::createGUID();
1324 $owner = User::getOwnerDataById($uid);
1325 $data = ['@context' => ActivityPub::CONTEXT,
1328 'actor' => $owner['url'],
1329 'object' => ['id' => $object_id, 'type' => 'Follow',
1330 'actor' => $owner['url'],
1331 'object' => $profile['url']],
1332 'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1333 'to' => [$profile['url']]];
1335 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1337 $signed = LDSignature::sign($data, $owner);
1338 HTTPSignature::transmit($signed, $profile['inbox'], $uid);