friendica/src/Protocol/ActivityPub/Transmitter.php

2144 lines
62 KiB
PHP
Raw Normal View History

<?php
/**
2021-03-29 08:40:20 +02:00
* @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
*/
namespace Friendica\Protocol\ActivityPub;
use Friendica\Content\Feature;
use Friendica\Content\Text\BBCode;
use Friendica\Core\Cache\Duration;
2018-10-29 22:20:46 +01:00
use Friendica\Core\Logger;
use Friendica\Core\Protocol;
2019-11-02 22:29:16 +01:00
use Friendica\Core\System;
use Friendica\Database\DBA;
use Friendica\DI;
use Friendica\Model\APContact;
use Friendica\Model\Contact;
use Friendica\Model\Conversation;
use Friendica\Model\GServer;
use Friendica\Model\Item;
use Friendica\Model\Photo;
use Friendica\Model\Post;
use Friendica\Model\Profile;
2020-04-26 17:24:58 +02:00
use Friendica\Model\Tag;
use Friendica\Model\User;
use Friendica\Network\HTTPException;
2019-11-02 22:29:16 +01:00
use Friendica\Protocol\Activity;
use Friendica\Protocol\ActivityPub;
use Friendica\Protocol\Relay;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\HTTPSignature;
use Friendica\Util\JsonLD;
use Friendica\Util\LDSignature;
use Friendica\Util\Map;
2018-11-22 23:23:31 +01:00
use Friendica\Util\Network;
use Friendica\Util\XML;
/**
2020-01-19 07:05:23 +01:00
* ActivityPub Transmitter Protocol class
2018-10-03 11:53:12 +02:00
*
* To-Do:
* @todo Undo Announce
*/
class Transmitter
{
/**
* Add relay servers to the list of inboxes
*
* @param array $inboxes
* @return array inboxes with added relay servers
*/
2020-09-22 22:14:37 +02:00
public static function addRelayServerInboxes(array $inboxes = [])
{
foreach (Relay::getList(['inbox']) as $contact) {
$inboxes[$contact['inbox']] = $contact['inbox'];
}
return $inboxes;
}
/**
* Add relay servers to the list of inboxes
*
* @param array $inboxes
* @return array inboxes with added relay servers
*/
public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
{
$item = Post::selectFirst(['uid'], ['id' => $item_id]);
if (empty($item)) {
return $inboxes;
}
$relays = Relay::getDirectRelayList($item_id);
if (empty($relays)) {
return $inboxes;
}
foreach ($relays as $relay) {
$contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
$inboxes[$relay['batch']][] = $contact['id'] ?? 0;
}
return $inboxes;
}
/**
* Subscribe to a relay
*
* @param string $url Subscribe actor url
* @return bool success
*/
public static function sendRelayFollow(string $url)
{
2020-09-29 07:06:37 +02:00
$contact = Contact::getByURL($url);
if (empty($contact)) {
return false;
}
2020-09-29 07:06:37 +02:00
$activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
$success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
if ($success) {
2021-01-09 20:19:20 +01:00
DBA::update('contact', ['rel' => Contact::FRIEND], ['id' => $contact['id']]);
}
return $success;
}
/**
* Unsubscribe from a relay
*
2020-09-29 07:06:37 +02:00
* @param string $url Subscribe actor url
* @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
* @return bool success
*/
2020-09-29 07:06:37 +02:00
public static function sendRelayUndoFollow(string $url, bool $force = false)
{
2020-09-29 07:06:37 +02:00
$contact = Contact::getByURL($url);
if (empty($contact)) {
return false;
}
2020-09-29 07:06:37 +02:00
$success = self::sendContactUndo($url, $contact['id'], 0);
if ($success || $force) {
2021-01-09 20:19:20 +01:00
DBA::update('contact', ['rel' => Contact::NOTHING], ['id' => $contact['id']]);
}
return $success;
}
2021-07-04 08:30:54 +02:00
/**
* Collects a list of contacts of the given owner
*
* @param array $owner Owner array
* @param int|array $rel The relevant value(s) contact.rel should match
* @param string $module The name of the relevant AP endpoint module (followers|following)
* @param integer $page Page number
*
* @return array of owners
* @throws \Exception
*/
public static function getContacts($owner, $rel, $module, $page = null)
{
$parameters = [
'rel' => $rel,
'uid' => $owner['uid'],
'self' => false,
'deleted' => false,
'hidden' => false,
'archive' => false,
'pending' => false,
'blocked' => false,
];
$condition = DBA::buildCondition($parameters);
$sql = "SELECT COUNT(*) as `count`
FROM `contact`
JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
" . $condition;
$contacts = DBA::fetchFirst($sql, ...$parameters);
$modulePath = '/' . $module . '/';
$data = ['@context' => ActivityPub::CONTEXT];
$data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
$data['type'] = 'OrderedCollection';
$data['totalItems'] = $contacts['count'];
// When we hide our friends we will only show the pure number but don't allow more.
$profile = Profile::getByUID($owner['uid']);
if (!empty($profile['hide-friends'])) {
return $data;
}
if (empty($page)) {
$data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
} else {
$data['type'] = 'OrderedCollectionPage';
$list = [];
$sql = "SELECT `contact`.`url`
FROM `contact`
JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
" . $condition . "
LIMIT ?, ?";
$parameters[] = ($page - 1) * 100;
$parameters[] = 100;
$contacts = DBA::p($sql, ...$parameters);
while ($contact = DBA::fetch($contacts)) {
$list[] = $contact['url'];
}
2020-04-28 15:33:03 +02:00
DBA::close($contacts);
if (!empty($list)) {
$data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
}
$data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
$data['orderedItems'] = $list;
}
return $data;
}
/**
2018-10-06 06:18:40 +02:00
* Public posts for the given owner
*
2020-08-30 19:07:46 +02:00
* @param array $owner Owner array
* @param integer $page Page number
* @param string $requester URL of requesting account
*
* @return array of posts
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
2020-08-30 19:07:46 +02:00
public static function getOutbox($owner, $page = null, $requester = '')
{
$condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
2020-08-30 19:07:46 +02:00
if (!empty($requester)) {
$requester_id = Contact::getIdForURL($requester, $owner['uid']);
if (!empty($requester_id)) {
$permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
if (!empty($permissionSets)) {
$condition = ['psid' => array_merge($permissionSets->column('id'),
2020-08-30 19:07:46 +02:00
[DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
}
}
}
$condition = array_merge($condition,
['uid' => $owner['uid'],
'author-id' => Contact::getIdForURL($owner['url'], 0, false),
'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
'network' => Protocol::FEDERATED,
'parent-network' => Protocol::FEDERATED,
'origin' => true,
'deleted' => false,
'visible' => true]);
$count = Post::count($condition);
$data = ['@context' => ActivityPub::CONTEXT];
$data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
$data['type'] = 'OrderedCollection';
$data['totalItems'] = $count;
if (empty($page)) {
$data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
} else {
$data['type'] = 'OrderedCollectionPage';
$list = [];
$items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
while ($item = Post::fetch($items)) {
$activity = self::createActivityFromItem($item['id'], true);
$activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
// Only list "Create" activity objects here, no reshares
if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
$list[] = $activity['object'];
}
}
DBA::close($items);
if (!empty($list)) {
$data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
}
$data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
$data['orderedItems'] = $list;
}
return $data;
}
/**
* Return the service array containing information the used software and it's url
*
* @return array with service data
*/
private static function getService()
{
return ['type' => 'Service',
'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
'url' => DI::baseUrl()->get()];
}
/**
* Return the ActivityPub profile of the given user
*
* @param int $uid User ID
2018-10-04 14:53:41 +02:00
* @return array with profile data
* @throws HTTPException\NotFoundException
* @throws HTTPException\InternalServerErrorException
*/
public static function getProfile(int $uid): array
{
$owner = User::getOwnerDataById($uid);
if (!isset($owner['id'])) {
DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
throw new HTTPException\NotFoundException('User not found.');
}
$data = ['@context' => ActivityPub::CONTEXT];
$data['id'] = $owner['url'];
if (!empty($owner['guid'])) {
$data['diaspora:guid'] = $owner['guid'];
}
$data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
2021-07-04 08:30:54 +02:00
if ($uid != 0) {
$data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
$data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
$data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
$data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
} else {
$data['inbox'] = DI::baseUrl() . '/friendica/inbox';
}
$data['preferredUsername'] = $owner['nick'];
$data['name'] = $owner['name'];
if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
$data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
}
if (!empty($owner['about'])) {
$data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
}
if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
$data['vcard:hasInstantMessage'] = [];
if (!empty($owner['xmpp'])) {
$data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
}
if (!empty($owner['matrix'])) {
$data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
}
}
$data['url'] = $owner['url'];
$data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
2021-08-09 08:56:41 +02:00
$data['discoverable'] = (bool)$owner['net-publish'];
$data['publicKey'] = ['id' => $owner['url'] . '#main-key',
'owner' => $owner['url'],
'publicKeyPem' => $owner['pubkey']];
$data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
$data['icon'] = ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($owner['id'], '', $owner['updated'])];
$resourceid = Photo::ridFromURI($owner['photo']);
if (!empty($resourceid)) {
$photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
if (!empty($photo['type'])) {
$data['icon']['mediaType'] = $photo['type'];
}
}
if (!empty($owner['header'])) {
$data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
$resourceid = Photo::ridFromURI($owner['header']);
if (!empty($resourceid)) {
$photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
if (!empty($photo['type'])) {
$data['image']['mediaType'] = $photo['type'];
}
}
}
$custom_fields = [];
2021-09-14 04:00:40 +02:00
foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
$custom_fields[] = [
'type' => 'PropertyValue',
'name' => $profile_field->label,
'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
];
};
if (!empty($custom_fields)) {
$data['attachment'] = $custom_fields;
}
$data['generator'] = self::getService();
// tags: https://kitty.town/@inmysocks/100656097926961126.json
return $data;
}
/**
* @param string $username
* @return array
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getDeletedUser($username)
{
return [
'@context' => ActivityPub::CONTEXT,
'id' => DI::baseUrl() . '/profile/' . $username,
'type' => 'Tombstone',
'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
];
}
/**
2018-10-06 06:18:40 +02:00
* Returns an array with permissions of a given item array
*
* @param array $item
*
* @return array with permissions
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function fetchPermissionBlockFromConversation($item)
{
if (empty($item['thr-parent'])) {
return [];
}
$condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
$conversation = DBA::selectFirst('conversation', ['source'], $condition);
if (!DBA::isResult($conversation)) {
return [];
}
$activity = json_decode($conversation['source'], true);
$actor = JsonLD::fetchElement($activity, 'actor', 'id');
if (!empty($actor)) {
$permissions['to'][] = $actor;
$profile = APContact::getByURL($actor);
} else {
$profile = [];
}
$item_profile = APContact::getByURL($item['author-link']);
$exclude[] = $item['author-link'];
if ($item['gravity'] == GRAVITY_PARENT) {
$exclude[] = $item['owner-link'];
}
foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
if (empty($activity[$element])) {
continue;
}
if (is_string($activity[$element])) {
$activity[$element] = [$activity[$element]];
}
foreach ($activity[$element] as $receiver) {
if (empty($receiver)) {
continue;
}
2020-03-05 23:03:24 +01:00
if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
$permissions[$element][] = $item_profile['followers'];
} elseif (!in_array($receiver, $exclude)) {
$permissions[$element][] = $receiver;
}
}
}
return $permissions;
}
2020-12-11 07:35:38 +01:00
/**
* Check if the given item id is from ActivityPub
*
* @param integer $item_id
* @return boolean "true" if the post is from ActivityPub
*/
2020-12-11 21:20:27 +01:00
private static function isAPPost(int $item_id)
{
2020-12-11 07:35:38 +01:00
if (empty($item_id)) {
return false;
}
return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
2020-12-11 07:35:38 +01:00
}
/**
2018-10-06 06:18:40 +02:00
* Creates an array of permissions from an item thread
*
2019-03-14 19:44:41 +01:00
* @param array $item Item array
* @param boolean $blindcopy addressing via "bcc" or "cc"?
* @param integer $last_id Last item id for adding receivers
* @param boolean $forum_mode "true" means that we are sending content to a forum
*
2018-10-04 14:53:41 +02:00
* @return array with permission data
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
2019-03-14 19:44:41 +01:00
private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
{
if ($last_id == 0) {
$last_id = $item['id'];
}
$always_bcc = false;
// Check if we should always deliver our stuff via BCC
if (!empty($item['uid'])) {
2020-08-10 21:44:37 +02:00
$profile = User::getOwnerDataById($item['uid']);
if (!empty($profile)) {
$always_bcc = $profile['hide-friends'];
}
}
if (DI::config()->get('system', 'ap_always_bcc')) {
$always_bcc = true;
}
2020-12-11 07:35:38 +01:00
if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
// Will be activated in a later step
2019-07-01 20:00:55 +02:00
$networks = Protocol::FEDERATED;
} else {
// For now only send to these contacts:
$networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
}
2018-10-24 22:06:57 +02:00
$data = ['to' => [], 'cc' => [], 'bcc' => []];
if ($item['gravity'] == GRAVITY_PARENT) {
$actor_profile = APContact::getByURL($item['owner-link']);
} else {
$actor_profile = APContact::getByURL($item['author-link']);
}
2021-06-05 20:38:21 +02:00
$exclusive = false;
2020-05-01 08:01:22 +02:00
$terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
2020-03-02 08:57:23 +01:00
if ($item['private'] != Item::PRIVATE) {
// Directly mention the original author upon a quoted reshare.
// Else just ensure that the original author receives the reshare.
$announce = self::getAnnounceArray($item);
if (!empty($announce['comment'])) {
$data['to'][] = $announce['actor']['url'];
} elseif (!empty($announce)) {
$data['cc'][] = $announce['actor']['url'];
}
$data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
2020-03-02 08:57:23 +01:00
// Check if the item is completely public or unlisted
if ($item['private'] == Item::PUBLIC) {
$data['to'][] = ActivityPub::PUBLIC_COLLECTION;
} else {
$data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
}
foreach ($terms as $term) {
$profile = APContact::getByURL($term['url'], false);
if (!empty($profile)) {
2021-06-05 20:38:21 +02:00
if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
$exclusive = true;
2021-06-06 15:25:42 +02:00
if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
$data['cc'][] = $profile['followers'];
}
2021-06-05 20:38:21 +02:00
}
$data['to'][] = $profile['url'];
}
}
} else {
$receiver_list = Item::enumeratePermissions($item, true);
foreach ($terms as $term) {
$cid = Contact::getIdForURL($term['url'], $item['uid']);
if (!empty($cid) && in_array($cid, $receiver_list)) {
$contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
continue;
}
if (!empty($profile = APContact::getByURL($contact['url'], false))) {
$data['to'][] = $profile['url'];
}
}
}
foreach ($receiver_list as $receiver) {
$contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
continue;
}
if (!empty($profile = APContact::getByURL($contact['url'], false))) {
if ($contact['hidden'] || $always_bcc) {
$data['bcc'][] = $profile['url'];
} else {
$data['cc'][] = $profile['url'];
}
}
}
}
if (!empty($item['parent'])) {
$parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
while ($parent = Post::fetch($parents)) {
if ($parent['gravity'] == GRAVITY_PARENT) {
$profile = APContact::getByURL($parent['owner-link'], false);
if (!empty($profile)) {
if ($item['gravity'] != GRAVITY_PARENT) {
// Comments to forums are directed to the forum
// But comments to forums aren't directed to the followers collection
2020-08-09 20:42:25 +02:00
// This rule is only valid when the actor isn't the forum.
// The forum needs to transmit their content to their followers.
if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
$data['to'][] = $profile['url'];
} else {
$data['cc'][] = $profile['url'];
2020-04-04 19:59:08 +02:00
if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
$data['cc'][] = $actor_profile['followers'];
}
}
2021-06-05 20:38:21 +02:00
} elseif (!$exclusive) {
2021-06-06 12:07:21 +02:00
// Public thread parent post always are directed to the followers.
// This mustn't be done by posts that are directed to forum servers via the exclusive mention.
// But possibly in that case we could add the "followers" collection of the forum to the message.
2020-03-02 08:57:23 +01:00
if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
$data['cc'][] = $actor_profile['followers'];
}
}
}
}
// Don't include data from future posts
if ($parent['id'] >= $last_id) {
continue;
}
$profile = APContact::getByURL($parent['author-link'], false);
if (!empty($profile)) {
if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
$data['to'][] = $profile['url'];
} else {
$data['cc'][] = $profile['url'];
}
}
}
DBA::close($parents);
}
$data['to'] = array_unique($data['to']);
$data['cc'] = array_unique($data['cc']);
2018-10-24 22:06:57 +02:00
$data['bcc'] = array_unique($data['bcc']);
if (($key = array_search($item['author-link'], $data['to'])) !== false) {
unset($data['to'][$key]);
}
if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
unset($data['cc'][$key]);
}
2018-10-24 22:06:57 +02:00
if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
unset($data['bcc'][$key]);
}
foreach ($data['to'] as $to) {
if (($key = array_search($to, $data['cc'])) !== false) {
unset($data['cc'][$key]);
}
2018-10-24 22:06:57 +02:00
if (($key = array_search($to, $data['bcc'])) !== false) {
unset($data['bcc'][$key]);
}
}
2018-10-24 22:06:57 +02:00
foreach ($data['cc'] as $cc) {
if (($key = array_search($cc, $data['bcc'])) !== false) {
unset($data['bcc'][$key]);
}
}
$receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
if (!$blindcopy) {
unset($receivers['bcc']);
}
return $receivers;
}
/**
* Check if an inbox is archived
*
* @param string $url Inbox url
*
* @return boolean "true" if inbox is archived
*/
2020-11-23 20:25:22 +01:00
public static function archivedInbox($url)
{
return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
}
/**
* Check if a given contact should be delivered via AP
*
2021-07-04 08:30:54 +02:00
* @param array $contact
* @param array $networks
* @return bool
* @throws Exception
*/
private static function isAPContact(array $contact, array $networks)
{
if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
return true;
}
return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
}
/**
2018-10-06 06:18:40 +02:00
* Fetches a list of inboxes of followers of a given user
*
2019-01-06 22:06:53 +01:00
* @param integer $uid User ID
* @param boolean $personal fetch personal inboxes
2020-12-11 07:35:38 +01:00
* @param boolean $all_ap Retrieve all AP enabled inboxes
*
* @return array of follower inboxes
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
2020-12-11 07:35:38 +01:00
public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
{
$inboxes = [];
2020-08-10 21:44:37 +02:00
$isforum = false;
if (!empty($item['uid'])) {
$profile = User::getOwnerDataById($item['uid']);
if (!empty($profile)) {
$isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
}
}
2020-12-11 07:35:38 +01:00
if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
// Will be activated in a later step
2019-07-01 20:00:55 +02:00
$networks = Protocol::FEDERATED;
} else {
// For now only send to these contacts:
$networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
}
$condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
if (!empty($uid)) {
$condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
}
$contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
while ($contact = DBA::fetch($contacts)) {
if (!self::isAPContact($contact, $networks)) {
continue;
}
if ($isforum && ($contact['network'] == Protocol::DFRN)) {
2020-08-10 21:44:37 +02:00
continue;
}
2018-11-22 23:23:31 +01:00
if (Network::isUrlBlocked($contact['url'])) {
continue;
}
$profile = APContact::getByURL($contact['url'], false);
if (!empty($profile)) {
2021-05-26 11:24:37 +02:00
if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
$target = $profile['inbox'];
} else {
$target = $profile['sharedinbox'];
}
if (!self::archivedInbox($target)) {
$inboxes[$target][] = $contact['id'];
}
}
}
DBA::close($contacts);
return $inboxes;
}
/**
2018-10-06 06:18:40 +02:00
* Fetches an array of inboxes for the given item and user
*
2019-03-14 19:44:41 +01:00
* @param array $item Item array
* @param integer $uid User ID
* @param boolean $personal fetch personal inboxes
* @param integer $last_id Last item id for adding receivers
* @param boolean $forum_mode "true" means that we are sending content to a forum
* @return array with inboxes
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
2019-03-14 19:44:41 +01:00
public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
{
2019-03-14 19:44:41 +01:00
$permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
if (empty($permissions)) {
return [];
}
$inboxes = [];
if ($item['gravity'] == GRAVITY_ACTIVITY) {
$item_profile = APContact::getByURL($item['author-link'], false);
} else {
$item_profile = APContact::getByURL($item['owner-link'], false);
}
if (empty($item_profile)) {
return [];
}
2020-08-09 20:42:25 +02:00
$profile_uid = User::getIdForURL($item_profile['url']);
foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
if (empty($permissions[$element])) {
continue;
}
2018-10-24 21:19:51 +02:00
$blindcopy = in_array($element, ['bto', 'bcc']);
foreach ($permissions[$element] as $receiver) {
if (empty($receiver) || Network::isUrlBlocked($receiver)) {
2018-11-22 23:31:48 +01:00
continue;
}
2020-08-09 20:42:25 +02:00
if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
2020-12-11 07:35:38 +01:00
$inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
} else {
$profile = APContact::getByURL($receiver, false);
if (!empty($profile)) {
$contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
2021-05-26 11:24:37 +02:00
if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
$target = $profile['inbox'];
} else {
$target = $profile['sharedinbox'];
}
if (!self::archivedInbox($target)) {
$inboxes[$target][] = $contact['id'] ?? 0;
}
}
}
}
}
return $inboxes;
}
/**
* Creates an array in the structure of the item table for a given mail id
*
* @param integer $mail_id
*
* @return array
* @throws \Exception
*/
2021-05-20 06:39:45 +02:00
public static function ItemArrayFromMail($mail_id, $use_title = false)
{
$mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
2019-11-19 11:02:35 +01:00
if (!DBA::isResult($mail)) {
return [];
}
2021-05-22 15:37:04 +02:00
$reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
2021-08-30 14:29:09 +02:00
if (!DBA::isResult($reply)) {
$reply = $mail;
}
// Making the post more compatible for Mastodon by:
// - Making it a note and not an article (no title)
// - Moving the title into the "summary" field that is used as a "content warning"
2021-05-20 06:39:45 +02:00
2021-05-22 15:37:04 +02:00
if (!$use_title) {
2021-05-20 06:39:45 +02:00
$mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
$mail['title'] = '';
}
$mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
2021-05-22 15:37:04 +02:00
$mail['owner-id'] = $mail['author-id'];
2021-05-20 06:39:45 +02:00
$mail['allow_cid'] = '<'.$mail['contact-id'].'>';
$mail['allow_gid'] = '';
$mail['deny_cid'] = '';
$mail['deny_gid'] = '';
$mail['private'] = Item::PRIVATE;
$mail['deleted'] = false;
$mail['edited'] = $mail['created'];
2021-05-22 15:37:04 +02:00
$mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
$mail['parent-uri'] = $reply['uri'];
$mail['parent-uri-id'] = $reply['uri-id'];
2021-05-20 06:39:45 +02:00
$mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
$mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
$mail['event-type'] = '';
$mail['language'] = '';
$mail['parent'] = 0;
return $mail;
}
/**
* Creates an activity array for a given mail id
*
* @param integer $mail_id
* @param boolean $object_mode Is the activity item is used inside another object?
*
* @return array of activity
* @throws \Exception
*/
public static function createActivityFromMail($mail_id, $object_mode = false)
{
$mail = self::ItemArrayFromMail($mail_id);
2020-09-18 14:08:40 +02:00
if (empty($mail)) {
return [];
}
$object = self::createNote($mail);
if (!$object_mode) {
$data = ['@context' => ActivityPub::CONTEXT];
} else {
$data = [];
}
2020-05-27 21:05:33 +02:00
$data['id'] = $mail['uri'] . '/Create';
$data['type'] = 'Create';
$data['actor'] = $mail['author-link'];
$data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
$data['instrument'] = self::getService();
$data = array_merge($data, self::createPermissionBlockForItem($mail, true));
if (empty($data['to']) && !empty($data['cc'])) {
$data['to'] = $data['cc'];
}
if (empty($data['to']) && !empty($data['bcc'])) {
$data['to'] = $data['bcc'];
}
unset($data['cc']);
unset($data['bcc']);
$object['to'] = $data['to'];
2019-11-22 20:47:35 +01:00
$object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
unset($object['cc']);
unset($object['bcc']);
$data['directMessage'] = true;
$data['object'] = $object;
$owner = User::getOwnerDataById($mail['uid']);
if (!$object_mode && !empty($owner)) {
return LDSignature::sign($data, $owner);
} else {
return $data;
}
}
/**
2018-10-06 06:18:40 +02:00
* Returns the activity type of a given item
*
* @param array $item
*
2018-10-04 14:53:41 +02:00
* @return string with activity type
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function getTypeOfItem($item)
{
$reshared = false;
// Only check for a reshare, if it is a real reshare and no quoted reshare
if (strpos($item['body'], "[share") === 0) {
$announce = self::getAnnounceArray($item);
$reshared = !empty($announce);
}
if ($reshared) {
2018-10-13 18:41:29 +02:00
$type = 'Announce';
} elseif ($item['verb'] == Activity::POST) {
if ($item['created'] == $item['edited']) {
$type = 'Create';
} else {
$type = 'Update';
}
} elseif ($item['verb'] == Activity::LIKE) {
$type = 'Like';
} elseif ($item['verb'] == Activity::DISLIKE) {
$type = 'Dislike';
} elseif ($item['verb'] == Activity::ATTEND) {
$type = 'Accept';
} elseif ($item['verb'] == Activity::ATTENDNO) {
$type = 'Reject';
} elseif ($item['verb'] == Activity::ATTENDMAYBE) {
$type = 'TentativeAccept';
} elseif ($item['verb'] == Activity::FOLLOW) {
$type = 'Follow';
} elseif ($item['verb'] == Activity::TAG) {
$type = 'Add';
2020-08-09 20:42:25 +02:00
} elseif ($item['verb'] == Activity::ANNOUNCE) {
$type = 'Announce';
} else {
$type = '';
}
return $type;
}
2018-10-05 23:00:40 +02:00
/**
2018-10-06 06:18:40 +02:00
* Creates the activity or fetches it from the cache
2018-10-05 23:00:40 +02:00
*
* @param integer $item_id
2019-01-06 22:06:53 +01:00
* @param boolean $force Force new cache entry
2018-10-05 23:00:40 +02:00
*
* @return array with the activity
2019-01-06 22:06:53 +01:00
* @throws \Exception
2018-10-05 23:00:40 +02:00
*/
public static function createCachedActivityFromItem($item_id, $force = false)
2018-10-05 23:00:40 +02:00
{
2018-10-06 04:09:27 +02:00
$cachekey = 'APDelivery:createActivity:' . $item_id;
if (!$force) {
$data = DI::cache()->get($cachekey);
if (!is_null($data)) {
return $data;
}
2018-10-05 23:00:40 +02:00
}
$data = self::createActivityFromItem($item_id);
2018-10-05 23:00:40 +02:00
DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
2018-10-05 23:00:40 +02:00
return $data;
}
/**
2018-10-06 06:18:40 +02:00
* Creates an activity array for a given item id
*
* @param integer $item_id
* @param boolean $object_mode Is the activity item is used inside another object?
*
* @return false|array
2019-01-06 22:06:53 +01:00
* @throws \Exception
*/
public static function createActivityFromItem(int $item_id, bool $object_mode = false)
{
2020-08-09 20:42:25 +02:00
Logger::info('Fetching activity', ['item' => $item_id]);
$item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
if (!DBA::isResult($item)) {
return false;
}
2020-08-09 20:42:25 +02:00
// In case of a forum post ensure to return the original post if author and forum are on the same machine
if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
2020-08-09 20:42:25 +02:00
$author = Contact::getById($item['author-id'], ['nurl']);
if (!empty($author['nurl'])) {
$self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
if (!empty($self['uid'])) {
$forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
if (DBA::isResult($forum_item)) {
2021-07-04 08:30:54 +02:00
$item = $forum_item;
2020-11-12 06:17:48 +01:00
}
2020-08-09 20:42:25 +02:00
}
}
}
2020-11-12 06:17:48 +01:00
if (empty($item['uri-id'])) {
Logger::warning('Item without uri-id', ['item' => $item]);
return false;
}
2021-03-24 23:22:14 +01:00
if (!$item['deleted']) {
$condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
$conversation = DBA::selectFirst('conversation', ['source'], $condition);
if (!$item['origin'] && DBA::isResult($conversation)) {
$data = json_decode($conversation['source'], true);
if (!empty($data['type'])) {
if (in_array($data['type'], ['Create', 'Update'])) {
if ($object_mode) {
unset($data['@context']);
unset($data['signature']);
}
Logger::info('Return stored conversation', ['item' => $item_id]);
return $data;
} elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
if (!empty($data['@context'])) {
$context = $data['@context'];
unset($data['@context']);
}
unset($data['actor']);
$object = $data;
2020-12-11 21:20:27 +01:00
}
}
}
}
2020-12-11 21:20:27 +01:00
$type = self::getTypeOfItem($item);
if (!$object_mode) {
$data = ['@context' => $context ?? ActivityPub::CONTEXT];
if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
$type = 'Undo';
} elseif ($item['deleted']) {
$type = 'Delete';
}
} else {
$data = [];
}
2021-03-24 23:22:14 +01:00
if ($type == 'Delete') {
$data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
} elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
$data['id'] = $item['uri'];
} else {
$data['id'] = $item['uri'] . '/' . $type;
}
$data['type'] = $type;
2019-03-14 19:44:41 +01:00
2020-08-09 20:42:25 +02:00
if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
2019-03-14 19:44:41 +01:00
$data['actor'] = $item['author-link'];
} else {
$data['actor'] = $item['owner-link'];
}
$data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
$data['instrument'] = self::getService();
2018-10-24 21:19:51 +02:00
$data = array_merge($data, self::createPermissionBlockForItem($item, false));
2018-10-13 18:41:29 +02:00
if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
$data['object'] = $object ?? self::createNote($item);
} elseif ($data['type'] == 'Add') {
$data = self::createAddTag($item, $data);
2018-10-13 18:41:29 +02:00
} elseif ($data['type'] == 'Announce') {
2020-08-09 20:42:25 +02:00
if ($item['verb'] == ACTIVITY::ANNOUNCE) {
$data['object'] = $item['thr-parent'];
} else {
$data = self::createAnnounce($item, $data);
}
} elseif ($data['type'] == 'Follow') {
$data['object'] = $item['parent-uri'];
} elseif ($data['type'] == 'Undo') {
$data['object'] = self::createActivityFromItem($item_id, true);
} else {
$data['diaspora:guid'] = $item['guid'];
if (!empty($item['signed_text'])) {
$data['diaspora:like'] = $item['signed_text'];
}
$data['object'] = $item['thr-parent'];
}
if (!empty($item['contact-uid'])) {
$uid = $item['contact-uid'];
} else {
$uid = $item['uid'];
}
$owner = User::getOwnerDataById($uid);
2020-08-09 20:42:25 +02:00
Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
// We don't sign if we aren't the actor. This is important for relaying content especially for forums
if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
return LDSignature::sign($data, $owner);
} else {
return $data;
}
/// @todo Create "conversation" entry
}
/**
* Creates a location entry for a given item array
*
* @param array $item
*
* @return array with location array
*/
private static function createLocation($item)
{
$location = ['type' => 'Place'];
if (!empty($item['location'])) {
$location['name'] = $item['location'];
}
$coord = [];
if (empty($item['coord'])) {
$coord = Map::getCoordinates($item['location']);
} else {
$coords = explode(' ', $item['coord']);
if (count($coords) == 2) {
$coord = ['lat' => $coords[0], 'lon' => $coords[1]];
}
}
if (!empty($coord['lat']) && !empty($coord['lon'])) {
$location['latitude'] = $coord['lat'];
$location['longitude'] = $coord['lon'];
}
return $location;
}
/**
2018-10-06 06:18:40 +02:00
* Returns a tag array for a given item array
*
* @param array $item
*
* @return array of tags
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function createTagList($item)
{
$tags = [];
2020-05-01 08:01:22 +02:00
$terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
foreach ($terms as $term) {
2020-04-26 17:24:58 +02:00
if ($term['type'] == Tag::HASHTAG) {
2020-05-01 17:27:56 +02:00
$url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
$tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
2020-04-26 17:24:58 +02:00
} else {
2020-07-15 19:06:48 +02:00
$contact = Contact::getByURL($term['url'], false, ['addr']);
2020-08-09 20:42:25 +02:00
if (empty($contact)) {
continue;
}
2018-10-03 20:27:01 +02:00
if (!empty($contact['addr'])) {
$mention = '@' . $contact['addr'];
} else {
$mention = '@' . $term['url'];
}
2018-10-03 20:27:01 +02:00
$tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
}
}
$announce = self::getAnnounceArray($item);
// Mention the original author upon commented reshares
if (!empty($announce['comment'])) {
$tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
}
return $tags;
}
2018-10-03 19:36:55 +02:00
/**
2018-10-06 06:18:40 +02:00
* Adds attachment data to the JSON document
2018-10-03 19:36:55 +02:00
*
2019-01-06 22:06:53 +01:00
* @param array $item Data of the item that is to be posted
* @param string $type Object type
*
2018-10-04 14:53:41 +02:00
* @return array with attachment data
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
2018-10-03 19:36:55 +02:00
*/
2018-10-04 07:26:00 +02:00
private static function createAttachmentList($item, $type)
2018-10-03 19:36:55 +02:00
{
$attachments = [];
$uriids = [$item['uri-id']];
$shared = BBCode::fetchShareAttributes($item['body']);
if (!empty($shared['guid'])) {
$shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
if (!empty($shared_item['uri-id'])) {
$uriids[] = $shared_item['uri-id'];
}
}
$urls = [];
foreach ($uriids as $uriid) {
foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
if (in_array($attachment['url'], $urls)) {
continue;
}
$urls[] = $attachment['url'];
2021-07-04 08:30:54 +02:00
$attach = ['type' => 'Document',
'mediaType' => $attachment['mimetype'],
'url' => $attachment['url'],
'name' => $attachment['description']];
2021-07-04 08:30:54 +02:00
if (!empty($attachment['height'])) {
$attach['height'] = $attachment['height'];
}
if (!empty($attachment['width'])) {
$attach['width'] = $attachment['width'];
}
2021-07-04 08:30:54 +02:00
if (!empty($attachment['preview'])) {
$attach['image'] = $attachment['preview'];
}
$attachments[] = $attach;
}
2018-10-03 19:36:55 +02:00
}
2018-10-04 07:26:00 +02:00
if ($type != 'Note') {
return $attachments;
}
foreach ($uriids as $uriid) {
foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
if (in_array($attachment['url'], $urls)) {
continue;
}
$urls[] = $attachment['url'];
2021-07-04 08:30:54 +02:00
$attach = ['type' => 'Document',
'mediaType' => $attachment['mimetype'],
'url' => $attachment['url'],
'name' => $attachment['description']];
2021-07-04 08:30:54 +02:00
if (!empty($attachment['height'])) {
$attach['height'] = $attachment['height'];
}
if (!empty($attachment['width'])) {
$attach['width'] = $attachment['width'];
}
if (!empty($attachment['preview'])) {
$attach['image'] = $attachment['preview'];
}
$attachments[] = $attach;
}
// Currently deactivated, since it creates side effects on Mastodon and Pleroma.
// It will be activated, once this cleared.
/*
foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
if (in_array($attachment['url'], $urls)) {
continue;
}
$urls[] = $attachment['url'];
$attachments[] = ['type' => 'Page',
'mediaType' => $attachment['mimetype'],
'url' => $attachment['url'],
'name' => $attachment['description']];
}*/
}
2018-10-03 19:36:55 +02:00
return $attachments;
}
2021-04-10 23:13:37 +02:00
/**
* Callback function to replace a Friendica style mention in a mention for a summary
*
* @param array $match Matching values for the callback
* @return string Replaced mention
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
private static function mentionAddrCallback($match)
{
if (empty($match[1])) {
return '';
}
2021-04-10 23:33:18 +02:00
$data = Contact::getByURL($match[1], false, ['addr']);
2021-04-10 23:13:37 +02:00
if (empty($data['addr'])) {
return $match[0];
}
return '@' . $data['addr'];
}
/**
* Remove image elements since they are added as attachment
*
* @param string $body
*
* @return string with removed images
*/
private static function removePictures($body)
{
// Simplify image codes
$body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
$body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
// Now remove local links
$body = preg_replace_callback(
'/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
function ($match) {
// We remove the link when it is a link to a local photo page
2019-11-12 00:13:36 +01:00
if (Photo::isLocalPage($match[1])) {
return '';
}
// otherwise we just return the link
return '[url]' . $match[1] . '[/url]';
},
$body
);
// Remove all pictures
$body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
return $body;
}
/**
2018-10-06 06:18:40 +02:00
* Fetches the "context" value for a givem item array from the "conversation" table
*
* @param array $item
*
* @return string with context url
2019-01-06 22:06:53 +01:00
* @throws \Exception
*/
private static function fetchContextURLForItem($item)
{
$conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
$context_uri = $conversation['conversation-href'];
} elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
$context_uri = $conversation['conversation-uri'];
} else {
$context_uri = $item['parent-uri'] . '#context';
}
return $context_uri;
}
/**
2018-10-06 06:18:40 +02:00
* Returns if the post contains sensitive content ("nsfw")
*
2020-04-26 17:24:58 +02:00
* @param integer $uri_id
*
* @return boolean
2019-01-06 22:06:53 +01:00
* @throws \Exception
*/
2020-04-26 17:24:58 +02:00
private static function isSensitive($uri_id)
2018-10-03 20:27:01 +02:00
{
2020-04-26 17:24:58 +02:00
return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
2018-10-03 20:27:01 +02:00
}
2018-10-26 06:13:26 +02:00
/**
* Creates event data
*
* @param array $item
*
* @return array with the event data
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
2018-10-26 06:13:26 +02:00
*/
2021-04-08 21:38:16 +02:00
private static function createEvent($item)
2018-10-26 06:13:26 +02:00
{
$event = [];
$event['name'] = $item['event-summary'];
$event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
2018-10-26 06:13:26 +02:00
$event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
if (!$item['event-nofinish']) {
$event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
}
if (!empty($item['event-location'])) {
$item['location'] = $item['event-location'];
$event['location'] = self::createLocation($item);
}
2021-04-08 21:38:16 +02:00
$event['dfrn:adjust'] = (bool)$item['event-adjust'];
2018-10-26 06:13:26 +02:00
return $event;
}
/**
2018-10-06 06:18:40 +02:00
* Creates a note/article object array
*
* @param array $item
*
2018-10-04 14:53:41 +02:00
* @return array with the object data
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function createNote($item)
{
2019-11-19 11:02:35 +01:00
if (empty($item)) {
return [];
}
2018-10-26 06:13:26 +02:00
if ($item['event-type'] == 'event') {
$type = 'Event';
} elseif (!empty($item['title'])) {
$type = 'Article';
} else {
$type = 'Note';
}
if ($item['deleted']) {
$type = 'Tombstone';
}
$data = [];
$data['id'] = $item['uri'];
$data['type'] = $type;
if ($item['deleted']) {
return $data;
}
$data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
if ($item['uri'] != $item['thr-parent']) {
$data['inReplyTo'] = $item['thr-parent'];
} else {
$data['inReplyTo'] = null;
}
$data['diaspora:guid'] = $item['guid'];
$data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
if ($item['created'] != $item['edited']) {
$data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
}
$data['url'] = $item['plink'];
$data['attributedTo'] = $item['author-link'];
2020-04-26 17:24:58 +02:00
$data['sensitive'] = self::isSensitive($item['uri-id']);
$data['context'] = self::fetchContextURLForItem($item);
if (!empty($item['title'])) {
2018-10-06 15:28:17 +02:00
$data['name'] = BBCode::toPlaintext($item['title'], false);
}
$permission_block = self::createPermissionBlockForItem($item, false);
$body = $item['body'];
if ($type == 'Note') {
$body = $item['raw-body'] ?? self::removePictures($body);
}
2021-05-22 18:11:10 +02:00
/**
* @todo Improve the automated summary
* This part is currently deactivated. The automated summary seems to be more
* confusing than helping. But possibly we will find a better way.
* So the code is left here for now as a reminder
2021-07-04 08:30:54 +02:00
*
2021-05-22 18:11:10 +02:00
* } elseif (($type == 'Article') && empty($data['summary'])) {
* $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
* $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
* $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
* }
*/
if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
2020-11-08 20:21:08 +01:00
$body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
}
2018-10-26 06:13:26 +02:00
if ($type == 'Event') {
$data = array_merge($data, self::createEvent($item));
} else {
$body = BBCode::setMentionsToNicknames($body);
2019-11-17 19:12:20 +01:00
$data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
2018-10-26 06:13:26 +02:00
}
2018-10-19 07:27:54 +02:00
// The regular "content" field does contain a minimized HTML. This is done since systems like
// Mastodon has got problems with - for example - embedded pictures.
// The contentMap does contain the unmodified HTML.
$language = self::getLanguage($item);
if (!empty($language)) {
$richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
$richbody = BBCode::removeAttachment($richbody);
$data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
}
$data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
$data['diaspora:comment'] = $item['signed_text'];
}
2018-10-04 07:26:00 +02:00
$data['attachment'] = self::createAttachmentList($item, $type);
$data['tag'] = self::createTagList($item);
2018-10-26 06:13:26 +02:00
if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
$data['location'] = self::createLocation($item);
}
if (!empty($item['app'])) {
$data['generator'] = ['type' => 'Application', 'name' => $item['app']];
}
$data = array_merge($data, $permission_block);
return $data;
}
/**
* Fetches the language from the post, the user or the system.
*
* @param array $item
*
* @return string language string
*/
2020-01-04 22:48:26 +01:00
private static function getLanguage(array $item)
{
// Try to fetch the language from the post itself
if (!empty($item['language'])) {
$languages = array_keys(json_decode($item['language'], true));
if (!empty($languages[0])) {
return $languages[0];
}
}
// Otherwise use the user's language
if (!empty($item['uid'])) {
$user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
if (!empty($user['language'])) {
return $user['language'];
}
}
// And finally just use the system language
return DI::config()->get('system', 'language');
}
/**
* Creates an an "add tag" entry
*
* @param array $item
* @param array $data activity data
*
* @return array with activity data for adding tags
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function createAddTag($item, $data)
{
2020-04-27 16:35:50 +02:00
$object = XML::parseString($item['object']);
$target = XML::parseString($item["target"]);
$data['diaspora:guid'] = $item['guid'];
$data['actor'] = $item['author-link'];
$data['target'] = (string)$target->id;
$data['summary'] = BBCode::toPlaintext($item['body']);
$data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
return $data;
}
2018-10-13 18:41:29 +02:00
/**
* Creates an announce object entry
*
* @param array $item
* @param array $data activity data
2018-10-13 18:41:29 +02:00
*
* @return array with activity data
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
2018-10-13 18:41:29 +02:00
*/
private static function createAnnounce($item, $data)
2018-10-13 18:41:29 +02:00
{
2019-07-20 23:32:19 +02:00
$orig_body = $item['body'];
$announce = self::getAnnounceArray($item);
if (empty($announce)) {
$data['type'] = 'Create';
$data['object'] = self::createNote($item);
return $data;
2018-10-13 18:41:29 +02:00
}
2019-12-04 09:08:48 +01:00
if (empty($announce['comment'])) {
// Pure announce, without a quote
$data['type'] = 'Announce';
$data['object'] = $announce['object']['uri'];
2019-12-04 09:08:48 +01:00
return $data;
2019-01-20 23:19:53 +01:00
}
2019-12-04 09:08:48 +01:00
// Quote
$data['type'] = 'Create';
$item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
$data['object'] = self::createNote($item);
2019-12-04 09:08:48 +01:00
/// @todo Finally descide how to implement this in AP. This is a possible way:
$data['object']['attachment'][] = self::createNote($announce['object']);
2019-12-04 09:08:48 +01:00
$data['object']['source']['content'] = $orig_body;
return $data;
2018-10-13 18:41:29 +02:00
}
/**
* Return announce related data if the item is an annunce
*
* @param array $item
*
* @return array
*/
public static function getAnnounceArray($item)
{
$reshared = Item::getShareArray($item);
if (empty($reshared['guid'])) {
return [];
}
$reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
2019-12-04 09:08:48 +01:00
if (!DBA::isResult($reshared_item)) {
return [];
}
if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
return [];
}
2019-12-04 09:08:48 +01:00
$profile = APContact::getByURL($reshared_item['author-link'], false);
if (empty($profile)) {
return [];
}
return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
}
2019-12-06 07:39:50 +01:00
/**
* Checks if the provided item array is an announce
*
* @param array $item
*
* @return boolean
*/
public static function isAnnounce($item)
{
if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
2020-08-09 20:42:25 +02:00
return true;
}
2019-12-06 07:39:50 +01:00
$announce = self::getAnnounceArray($item);
if (empty($announce)) {
return false;
}
return empty($announce['comment']);
}
/**
* Creates an activity id for a given contact id
*
* @param integer $cid Contact ID of target
*
* @return bool|string activity id
*/
public static function activityIDFromContact($cid)
{
$contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
if (!DBA::isResult($contact)) {
return false;
}
$hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
$uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
return DI::baseUrl() . '/activity/' . $uuid;
}
2018-10-06 20:42:26 +02:00
/**
* Transmits a contact suggestion to a given inbox
*
2019-01-06 22:06:53 +01:00
* @param integer $uid User ID
* @param string $inbox Target inbox
2018-10-06 20:42:26 +02:00
* @param integer $suggestion_id Suggestion ID
*
* @return boolean was the transmission successful?
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
2018-10-06 20:42:26 +02:00
*/
public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
{
$owner = User::getOwnerDataById($uid);
$suggestion = DI::fsuggest()->getById($suggestion_id);
2018-10-06 20:42:26 +02:00
$data = ['@context' => ActivityPub::CONTEXT,
'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2018-10-06 20:42:26 +02:00
'type' => 'Announce',
'actor' => $owner['url'],
'object' => $suggestion->url,
'content' => $suggestion->note,
'instrument' => self::getService(),
2018-10-06 20:42:26 +02:00
'to' => [ActivityPub::PUBLIC_COLLECTION],
'cc' => []];
$signed = LDSignature::sign($data, $owner);
Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
return HTTPSignature::transmit($signed, $inbox, $uid);
2018-10-06 20:42:26 +02:00
}
/**
* Transmits a profile relocation to a given inbox
*
2019-01-06 22:06:53 +01:00
* @param integer $uid User ID
* @param string $inbox Target inbox
*
* @return boolean was the transmission successful?
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function sendProfileRelocation($uid, $inbox)
{
$owner = User::getOwnerDataById($uid);
$data = ['@context' => ActivityPub::CONTEXT,
'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
'type' => 'dfrn:relocate',
'actor' => $owner['url'],
'object' => $owner['url'],
'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'instrument' => self::getService(),
'to' => [ActivityPub::PUBLIC_COLLECTION],
'cc' => []];
$signed = LDSignature::sign($data, $owner);
Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
return HTTPSignature::transmit($signed, $inbox, $uid);
}
/**
2018-10-06 06:18:40 +02:00
* Transmits a profile deletion to a given inbox
*
2019-01-06 22:06:53 +01:00
* @param integer $uid User ID
* @param string $inbox Target inbox
*
* @return boolean was the transmission successful?
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
2018-10-03 17:41:51 +02:00
public static function sendProfileDeletion($uid, $inbox)
{
$owner = User::getOwnerDataById($uid);
if (empty($owner)) {
Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
return false;
}
if (empty($owner['uprvkey'])) {
Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
return false;
}
$data = ['@context' => ActivityPub::CONTEXT,
'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
'type' => 'Delete',
'actor' => $owner['url'],
2018-10-03 11:15:38 +02:00
'object' => $owner['url'],
'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'instrument' => self::getService(),
'to' => [ActivityPub::PUBLIC_COLLECTION],
'cc' => []];
$signed = LDSignature::sign($data, $owner);
Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
return HTTPSignature::transmit($signed, $inbox, $uid);
}
/**
2018-10-06 06:18:40 +02:00
* Transmits a profile change to a given inbox
*
2019-01-06 22:06:53 +01:00
* @param integer $uid User ID
* @param string $inbox Target inbox
*
* @return boolean was the transmission successful?
* @throws HTTPException\InternalServerErrorException
* @throws HTTPException\NotFoundException
2019-01-06 22:06:53 +01:00
* @throws \ImagickException
*/
public static function sendProfileUpdate(int $uid, string $inbox): bool
{
$owner = User::getOwnerDataById($uid);
$profile = APContact::getByURL($owner['url']);
$data = ['@context' => ActivityPub::CONTEXT,
'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
'type' => 'Update',
'actor' => $owner['url'],
2018-10-03 17:50:21 +02:00
'object' => self::getProfile($uid),
'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'instrument' => self::getService(),
'to' => [$profile['followers']],
'cc' => []];
$signed = LDSignature::sign($data, $owner);
Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
return HTTPSignature::transmit($signed, $inbox, $uid);
}
/**
2018-10-06 06:18:40 +02:00
* Transmits a given activity to a target
*
2019-01-07 07:07:42 +01:00
* @param string $activity Type name
* @param string $target Target profile
* @param integer $uid User ID
* @return bool
2019-01-06 22:06:53 +01:00
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
* @throws \Exception
*/
public static function sendActivity($activity, $target, $uid, $id = '')
{
$profile = APContact::getByURL($target);
if (empty($profile['inbox'])) {
Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
return;
}
$owner = User::getOwnerDataById($uid);
if (empty($id)) {
$id = DI::baseUrl() . '/activity/' . System::createGUID();
}
$data = ['@context' => ActivityPub::CONTEXT,
'id' => $id,
'type' => $activity,
'actor' => $owner['url'],
'object' => $profile['url'],
'instrument' => self::getService(),
2019-01-14 13:10:11 +01:00
'to' => [$profile['url']]];
Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
$signed = LDSignature::sign($data, $owner);
return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
}
/**
* Transmits a "follow object" activity to a target
* This is a preparation for sending automated "follow" requests when receiving "Announce" messages
*
* @param string $object Object URL
* @param string $target Target profile
* @param integer $uid User ID
* @return bool
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
* @throws \Exception
*/
public static function sendFollowObject($object, $target, $uid = 0)
{
$profile = APContact::getByURL($target);
if (empty($profile['inbox'])) {
Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
return;
}
if (empty($uid)) {
// Fetch the list of administrators
$admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
// We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
$condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
$first_user = DBA::selectFirst('user', ['uid'], $condition);
$uid = $first_user['uid'];
}
$condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2019-02-10 19:03:01 +01:00
'author-id' => Contact::getPublicIdByUserId($uid)];
if (Post::exists($condition)) {
2019-02-10 19:03:01 +01:00
Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
return false;
}
$owner = User::getOwnerDataById($uid);
$data = ['@context' => ActivityPub::CONTEXT,
'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
'type' => 'Follow',
'actor' => $owner['url'],
'object' => $object,
'instrument' => self::getService(),
'to' => [$profile['url']]];
Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
$signed = LDSignature::sign($data, $owner);
return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
}
/**
2018-10-06 06:18:40 +02:00
* Transmit a message that the contact request had been accepted
*
2019-01-06 22:06:53 +01:00
* @param string $target Target profile
* @param $id
* @param integer $uid User ID
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
2018-10-03 17:41:51 +02:00
public static function sendContactAccept($target, $id, $uid)
{
$profile = APContact::getByURL($target);
if (empty($profile['inbox'])) {
Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
return;
}
$owner = User::getOwnerDataById($uid);
$data = ['@context' => ActivityPub::CONTEXT,
'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
'type' => 'Accept',
'actor' => $owner['url'],
'object' => [
'id' => (string)$id,
'type' => 'Follow',
'actor' => $profile['url'],
'object' => $owner['url']
],
'instrument' => self::getService(),
2019-01-14 13:10:11 +01:00
'to' => [$profile['url']]];
Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
$signed = LDSignature::sign($data, $owner);
HTTPSignature::transmit($signed, $profile['inbox'], $uid);
}
/**
2018-10-06 06:18:40 +02:00
* Reject a contact request or terminates the contact relation
*
2019-01-06 22:06:53 +01:00
* @param string $target Target profile
* @param $id
* @param integer $uid User ID
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
2018-10-03 17:41:51 +02:00
public static function sendContactReject($target, $id, $uid)
{
$profile = APContact::getByURL($target);
if (empty($profile['inbox'])) {
Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
return;
}
$owner = User::getOwnerDataById($uid);
$data = ['@context' => ActivityPub::CONTEXT,
'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
'type' => 'Reject',
'actor' => $owner['url'],
'object' => [
'id' => (string)$id,
'type' => 'Follow',
'actor' => $profile['url'],
'object' => $owner['url']
],
'instrument' => self::getService(),
2019-01-14 13:10:11 +01:00
'to' => [$profile['url']]];
Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
$signed = LDSignature::sign($data, $owner);
HTTPSignature::transmit($signed, $profile['inbox'], $uid);
}
/**
2018-10-06 06:18:40 +02:00
* Transmits a message that we don't want to follow this contact anymore
*
2019-01-06 22:06:53 +01:00
* @param string $target Target profile
* @param integer $uid User ID
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
* @throws \Exception
* @return bool success
*/
public static function sendContactUndo($target, $cid, $uid)
{
$profile = APContact::getByURL($target);
if (empty($profile['inbox'])) {
Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
return false;
}
$object_id = self::activityIDFromContact($cid);
if (empty($object_id)) {
return false;
}
$id = DI::baseUrl() . '/activity/' . System::createGUID();
$owner = User::getOwnerDataById($uid);
$data = ['@context' => ActivityPub::CONTEXT,
'id' => $id,
'type' => 'Undo',
'actor' => $owner['url'],
'object' => ['id' => $object_id, 'type' => 'Follow',
'actor' => $owner['url'],
'object' => $profile['url']],
'instrument' => self::getService(),
2019-01-14 13:10:11 +01:00
'to' => [$profile['url']]];
Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
$signed = LDSignature::sign($data, $owner);
return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
}
2020-11-08 20:21:08 +01:00
private static function prependMentions($body, int $uriid, string $authorLink)
{
$mentions = [];
foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2020-07-15 19:06:48 +02:00
$profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
if (!empty($profile['addr'])
&& $profile['contact-type'] != Contact::TYPE_COMMUNITY
&& !strstr($body, $profile['addr'])
&& !strstr($body, $tag['url'])
2020-11-08 20:21:08 +01:00
&& $tag['url'] !== $authorLink
) {
$mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
}
}
$mentions[] = $body;
return implode(' ', $mentions);
}
}