<?php
/**
- * @copyright Copyright (C) 2020, Friendica
+ * @copyright Copyright (C) 2010-2021, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
use Friendica\Model\APContact;
use Friendica\Model\Contact;
use Friendica\Model\Conversation;
+use Friendica\Model\GServer;
use Friendica\Model\Item;
use Friendica\Model\ItemURI;
use Friendica\Model\Profile;
use Friendica\Model\Photo;
+use Friendica\Model\Post;
use Friendica\Model\Tag;
use Friendica\Model\User;
use Friendica\Protocol\Activity;
use Friendica\Protocol\ActivityPub;
+use Friendica\Protocol\Relay;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\HTTPSignature;
-use Friendica\Util\Images;
use Friendica\Util\JsonLD;
use Friendica\Util\LDSignature;
use Friendica\Util\Map;
use Friendica\Util\Network;
use Friendica\Util\XML;
-require_once 'include/api.php';
-require_once 'mod/share.php';
-
/**
* ActivityPub Transmitter Protocol class
*
public static function addRelayServerInboxes(array $inboxes = [])
{
$contacts = DBA::select('apcontact', ['inbox'],
- ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))",
- 'Application', 0, Contact::FOLLOWER, Contact::FRIEND]);
+ ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)",
+ 'Application', 0, Contact::FRIEND]);
while ($contact = DBA::fetch($contacts)) {
- $inboxes[] = $contact['inbox'];
+ $inboxes[$contact['inbox']] = $contact['inbox'];
}
DBA::close($contacts);
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::getList($item_id, [], [Protocol::ACTIVITYPUB]);
+ 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
*
$activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
$success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
if ($success) {
- $rel = $contact['rel'] == Contact::SHARING ? Contact::FRIEND : Contact::FOLLOWER;
- DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
+ DBA::update('contact', ['rel' => Contact::FRIEND], ['id' => $contact['id']]);
}
return $success;
$success = self::sendContactUndo($url, $contact['id'], 0);
if ($success || $force) {
- $rel = $contact['rel'] == Contact::FRIEND ? Contact::SHARING : Contact::NOTHING;
- DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
+ DBA::update('contact', ['rel' => Contact::NOTHING], ['id' => $contact['id']]);
}
return $success;
'deleted' => false,
'hidden' => false,
'archive' => false,
- 'pending' => false
+ 'pending' => false,
+ 'blocked' => false,
];
$condition = DBA::buildCondition($parameters);
$condition = array_merge($condition,
['author-id' => $public_contact,
'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
- 'deleted' => false, 'visible' => true, 'moderated' => false]);
+ 'deleted' => false, 'visible' => true]);
- $count = DBA::count('item', $condition);
+ $count = Post::count($condition);
$data = ['@context' => ActivityPub::CONTEXT];
$data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
$condition['parent-network'] = Protocol::NATIVE_SUPPORT;
- $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
- while ($item = Item::fetch($items)) {
+ $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'];
$list[] = $activity['object'];
}
}
+ DBA::close($items);
if (!empty($list)) {
$data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
$activity = json_decode($conversation['source'], true);
$actor = JsonLD::fetchElement($activity, 'actor', 'id');
- $profile = APContact::getByURL($actor);
+ if (!empty($actor)) {
+ $permissions['to'][] = $actor;
+ $profile = APContact::getByURL($actor);
+ } else {
+ $profile = [];
+ }
$item_profile = APContact::getByURL($item['author-link']);
$exclude[] = $item['author-link'];
$exclude[] = $item['owner-link'];
}
- $permissions['to'][] = $actor;
-
foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
if (empty($activity[$element])) {
continue;
return $permissions;
}
+ /**
+ * Check if the given item id is from ActivityPub
+ *
+ * @param integer $item_id
+ * @return boolean "true" if the post is from ActivityPub
+ */
+ private static function isAPPost(int $item_id)
+ {
+ if (empty($item_id)) {
+ return false;
+ }
+
+ return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
+ }
+
/**
* Creates an array of permissions from an item thread
*
$always_bcc = true;
}
- if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
+ if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
// Will be activated in a later step
$networks = Protocol::FEDERATED;
} else {
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'], ['id' => $cid]);
- if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
+ $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
+ if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
continue;
}
}
foreach ($receiver_list as $receiver) {
- $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
- if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
+ $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($item['parent'])) {
- $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
- while ($parent = Item::fetch($parents)) {
+ $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)) {
*
* @return boolean "true" if inbox is archived
*/
- private static function archivedInbox($url)
+ public static function archivedInbox($url)
{
return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
}
+ /**
+ * Check if a given contact should be delivered via AP
+ *
+ * @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;
+ }
+
/**
* Fetches a list of inboxes of followers of a given user
*
* @param integer $uid User ID
* @param boolean $personal fetch personal inboxes
+ * @param boolean $all_ap Retrieve all AP enabled inboxes
*
* @return array of follower inboxes
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
- public static function fetchTargetInboxesforUser($uid, $personal = false)
+ public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
{
$inboxes = [];
}
}
- if (DI::config()->get('debug', 'total_ap_delivery')) {
+ if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
// Will be activated in a later step
$networks = Protocol::FEDERATED;
} else {
$networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
}
- $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
+ $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', ['url', 'network', 'protocol'], $condition);
+ $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
while ($contact = DBA::fetch($contacts)) {
if (Contact::isLocal($contact['url'])) {
continue;
}
- if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
+ if (!self::isAPContact($contact, $networks)) {
continue;
}
- if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
+ if ($isforum && ($contact['network'] == Protocol::DFRN)) {
continue;
}
$target = $profile['sharedinbox'];
}
if (!self::archivedInbox($target)) {
- $inboxes[$target] = $target;
+ $inboxes[$target][] = $contact['id'];
}
}
}
}
if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
- $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
+ $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
} else {
if (Contact::isLocal($receiver)) {
continue;
$profile = APContact::getByURL($receiver, false);
if (!empty($profile)) {
+ $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
+
if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
$target = $profile['inbox'];
} else {
$target = $profile['sharedinbox'];
}
if (!self::archivedInbox($target)) {
- $inboxes[$target] = $target;
+ $inboxes[$target][] = $contact['id'] ?? 0;
}
}
}
$mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
$mail['event-type'] = '';
- $mail['attach'] = '';
$mail['parent'] = 0;
* @param integer $item_id
* @param boolean $object_mode Is the activity item is used inside another object?
*
- * @return array of activity
+ * @return false|array
* @throws \Exception
*/
- public static function createActivityFromItem($item_id, $object_mode = false)
+ public static function createActivityFromItem(int $item_id, bool $object_mode = false)
{
Logger::info('Fetching activity', ['item' => $item_id]);
- $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
+ $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
if (!DBA::isResult($item)) {
return false;
}
// In case of a forum post ensure to return the original post if author and forum are on the same machine
- if (!empty($item['forum_mode'])) {
+ if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
$author = Contact::getById($item['author-id'], ['nurl']);
if (!empty($author['nurl'])) {
$self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
if (!empty($self['uid'])) {
- $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
+ $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
+ if (DBA::isResult($forum_item)) {
+ $item = $forum_item;
+ }
}
}
}
- if (empty($type)) {
+ if (empty($item['uri-id'])) {
+ Logger::warning('Item without uri-id', ['item' => $item]);
+ return false;
+ }
+
+ if (!$item['deleted']) {
$condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
$conversation = DBA::selectFirst('conversation', ['source'], $condition);
- if (DBA::isResult($conversation)) {
+ if (!$item['origin'] && DBA::isResult($conversation)) {
$data = json_decode($conversation['source'], true);
if (!empty($data['type'])) {
if (in_array($data['type'], ['Create', 'Update'])) {
}
}
}
-
- $type = self::getTypeOfItem($item);
}
+ $type = self::getTypeOfItem($item);
+
if (!$object_mode) {
$data = ['@context' => $context ?? ActivityPub::CONTEXT];
$data = [];
}
- if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
+ 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;
$attachments[] = $attachment;
}
*/
- $arr = explode('[/attach],', $item['attach']);
- if (count($arr)) {
- foreach ($arr as $r) {
- $matches = false;
- $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
- if ($cnt) {
- $attributes = ['type' => 'Document',
- 'mediaType' => $matches[3],
- 'url' => $matches[1],
- 'name' => null];
-
- if (trim($matches[4]) != '') {
- $attributes['name'] = trim($matches[4]);
- }
-
- $attachments[] = $attributes;
- }
- }
+ foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
+ $attachments[] = ['type' => 'Document',
+ 'mediaType' => $attachment['mimetype'],
+ 'url' => $attachment['url'],
+ 'name' => $attachment['description']];
}
if ($type != 'Note') {
return $attachments;
}
- // Simplify image codes
- $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
-
- // Grab all pictures without alternative descriptions and create attachments out of them
- if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
- foreach ($pictures[1] as $picture) {
- $imgdata = Images::getInfoFromURLCached($picture);
- if ($imgdata) {
- $attachments[] = ['type' => 'Document',
- 'mediaType' => $imgdata['mime'],
- 'url' => $picture,
- 'name' => null];
- }
- }
- }
-
- // Grab all pictures with alternative description and create attachments out of them
- if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
- foreach ($pictures as $picture) {
- $imgdata = Images::getInfoFromURLCached($picture[1]);
- if ($imgdata) {
- $attachments[] = ['type' => 'Document',
- 'mediaType' => $imgdata['mime'],
- 'url' => $picture[1],
- 'name' => $picture[2]];
- }
- }
+ foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
+ $attachments[] = ['type' => 'Document',
+ 'mediaType' => $attachment['mimetype'],
+ 'url' => $attachment['url'],
+ 'name' => $attachment['description']];
}
return $attachments;
return '';
}
- $data = Contact::getByURL($match[1], false, ['url', 'nick']);
+ $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
if (empty($data['nick'])) {
return $match[0];
}
- return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
+ return '[url=' . $data['url'] . ']@' . $data['nick'] . '[/url]';
+ }
+
+ /**
+ * 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 '';
+ }
+
+ $data = Contact::getByURL($match[1], false, ['addr']);
+ if (empty($data['addr'])) {
+ return $match[0];
+ }
+
+ return '@' . $data['addr'];
}
/**
* @return array with the event data
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
- public static function createEvent($item)
+ private static function createEvent($item)
{
$event = [];
$event['name'] = $item['event-summary'];
$event['location'] = self::createLocation($item);
}
+ $event['dfrn:adjust'] = (bool)$item['event-adjust'];
+
return $event;
}
$body = $item['body'];
- if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
- $body = self::prependMentions($body, $item['uri-id']);
- }
-
if ($type == 'Note') {
- $body = self::removePictures($body);
+ $body = $item['raw-body'] ?? self::removePictures($body);
} elseif (($type == 'Article') && empty($data['summary'])) {
- $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
+ $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')) {
+ $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
}
if ($type == 'Event') {
return [];
}
- $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
+ $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
if (!DBA::isResult($reshared_item)) {
return [];
}
$condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
'author-id' => Contact::getPublicIdByUserId($uid)];
- if (Item::exists($condition)) {
+ if (Post::exists($condition)) {
Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
return false;
}
return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
}
- private static function prependMentions($body, int $uriid)
+ private static function prependMentions($body, int $uriid, string $authorLink)
{
$mentions = [];
&& $profile['contact-type'] != Contact::TYPE_COMMUNITY
&& !strstr($body, $profile['addr'])
&& !strstr($body, $tag['url'])
+ && $tag['url'] !== $authorLink
) {
$mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
}