use Friendica\Util\Network;
use Friendica\Util\HTTPSignature;
use Friendica\Core\Protocol;
+use Friendica\Model\Conversation;
+use Friendica\Model\Contact;
use Friendica\Model\Item;
use Friendica\Model\User;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Crypto;
use Friendica\Content\Text\BBCode;
+use Friendica\Content\Text\HTML;
+use Friendica\Network\Probe;
/**
* @brief ActivityPub Protocol class
*
* https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
* https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
+ *
+ * Digest: https://tools.ietf.org/html/rfc5843
+ * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
+ *
+ * Part of the code for HTTP signing is taken from the Osada project.
+ *
+ *
+ * To-do:
+ *
+ * Receiver:
+ * - Activities: Undo, Update
+ * - Object Types: Person, Tombstome
+ *
+ * Transmitter:
+ * - Activities: Like, Dislike, Update, Undo
+ * - Object Tyoes: Article, Announce, Person, Tombstone
+ *
+ * General:
+ * - Message distribution
+ * - Endpoints: Outbox, Object, Follower, Following
*/
class ActivityPub
{
const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
- public static function transmit($content, $target, $uid)
+ public static function transmit($data, $target, $uid)
{
$owner = User::getOwnerDataById($uid);
return;
}
+ $content = json_encode($data);
+
$host = parse_url($target, PHP_URL_HOST);
$path = parse_url($target, PHP_URL_PATH);
$date = date('r');
$headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",headers="(request-target) host date",signature="' . $signature . '"';
$headers[] = 'Content-Type: application/activity+json';
-//print_r($headers);
-//die($signed_data);
-//$headers = [];
-// $headers = HTTPSignature::createSig('', $headers, $owner['uprvkey'], $owner['url'] . '#main-key', false, false, 'sha256');
Network::post($target, $content, $headers);
$return_code = BaseObject::getApp()->get_curl_code();
-echo $return_code."\n";
- print_r(BaseObject::getApp()->get_curl_headers());
- print_r($headers);
+
+ logger('Transmit to ' . $target . ' returned ' . $return_code);
}
/**
'toot' => 'http://joinmastodon.org/ns#']]];
$data['type'] = 'Create';
- $data['id'] = $item['plink'];
+ $data['id'] = $item['uri'];
$data['actor'] = $item['author-link'];
$data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
$data['object'] = self::createNote($item);
-// print_r($data);
-// print_r($item);
return $data;
}
{
$data = [];
$data['type'] = 'Note';
- $data['id'] = $item['plink'];
- //$data['context'] = $data['conversation'] = $item['parent-uri'];
+ $data['id'] = $item['uri'];
+
+ if ($item['uri'] != $item['thr-parent']) {
+ $data['inReplyTo'] = $item['thr-parent'];
+ }
+
+ $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
+ if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
+ $conversation_uri = $conversation['conversation-uri'];
+ } else {
+ $conversation_uri = $item['parent-uri'];
+ }
+
+ $data['context'] = $data['conversation'] = $conversation_uri;
$data['actor'] = $item['author-link'];
-// if (!$item['private']) {
-// $data['to'] = [];
-// $data['to'][] = '"https://pleroma.soykaf.com/users/heluecht"';
- $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
-// $data['cc'] = 'https://pleroma.soykaf.com/users/heluecht';
-// }
+ $data['to'] = [];
+ if (!$item['private']) {
+ $data['to'][] = 'https://www.w3.org/ns/activitystreams#Public';
+ }
$data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
$data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
$data['attributedTo'] = $item['author-link'];
- $data['title'] = BBCode::convert($item['title'], false, 7);
+ $data['name'] = BBCode::convert($item['title'], false, 7);
$data['content'] = BBCode::convert($item['body'], false, 7);
- //$data['summary'] = '';
- //$data['sensitive'] = false;
- //$data['emoji'] = [];
- //$data['tag'] = [];
- //$data['attachment'] = [];
+ $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
+ //$data['summary'] = ''; // Ignore by now
+ //$data['sensitive'] = false; // - Query NSFW
+ //$data['emoji'] = []; // Ignore by now
+ //$data['tag'] = []; /// @ToDo
+ //$data['attachment'] = []; // @ToDo
return $data;
}
+ public static function transmitActivity($activity, $target, $uid)
+ {
+ $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
+
+ $owner = User::getOwnerDataById($uid);
+
+ $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
+ 'id' => 'https://pirati.ca/activity/' . System::createGUID(),
+ 'type' => $activity,
+ 'actor' => $owner['url'],
+ 'object' => $profile['url']];
+
+ logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
+ return self::transmit($data, $profile['notify'], $uid);
+ }
+
+ public static function transmitContactActivity($activity, $target, $id, $uid)
+ {
+ $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
+
+ if (empty($id)) {
+ $id = 'https://pirati.ca/activity/' . System::createGUID();
+ }
+
+ $owner = User::getOwnerDataById($uid);
+ $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
+ 'id' => 'https://pirati.ca/activity/' . System::createGUID(),
+ 'type' => $activity,
+ 'actor' => $owner['url'],
+ 'object' => ['id' => $id, 'type' => 'Follow',
+ 'actor' => $owner['url'],
+ 'object' => $profile['url']]];
+
+ logger('Sending ' . $activity . ' to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
+ return self::transmit($data, $profile['notify'], $uid);
+ }
+
/**
* Fetches ActivityPub content from the given url
*
return false;
}
+ public static function verifySignature($content, $http_headers)
+ {
+ $object = json_decode($content, true);
+
+ if (empty($object)) {
+ return false;
+ }
+
+ $actor = self::processElement($object, 'actor', 'id');
+
+ $headers = [];
+ $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
+
+ // First take every header
+ foreach ($http_headers as $k => $v) {
+ $field = str_replace('_', '-', strtolower($k));
+ $headers[$field] = $v;
+ }
+
+ // Now add every http header
+ foreach ($http_headers as $k => $v) {
+ if (strpos($k, 'HTTP_') === 0) {
+ $field = str_replace('_', '-', strtolower(substr($k, 5)));
+ $headers[$field] = $v;
+ }
+ }
+
+ $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
+
+ if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
+ return false;
+ }
+
+ $signed_data = '';
+ foreach ($sig_block['headers'] as $h) {
+ if (array_key_exists($h, $headers)) {
+ $signed_data .= $h . ': ' . $headers[$h] . "\n";
+ }
+ }
+ $signed_data = rtrim($signed_data, "\n");
+
+ if (empty($signed_data)) {
+ return false;
+ }
+
+ $algorithm = null;
+
+ if ($sig_block['algorithm'] === 'rsa-sha256') {
+ $algorithm = 'sha256';
+ }
+
+ if ($sig_block['algorithm'] === 'rsa-sha512') {
+ $algorithm = 'sha512';
+ }
+
+ if (empty($algorithm)) {
+ return false;
+ }
+
+ $key = self::fetchKey($sig_block['keyId'], $actor);
+
+ if (empty($key)) {
+ return false;
+ }
+
+ if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
+ return false;
+ }
+
+ // Check the digest if it was part of the signed data
+ if (in_array('digest', $sig_block['headers'])) {
+ $digest = explode('=', $headers['digest'], 2);
+ if ($digest[0] === 'SHA-256') {
+ $hashalg = 'sha256';
+ }
+ if ($digest[0] === 'SHA-512') {
+ $hashalg = 'sha512';
+ }
+
+ /// @todo add all hashes from the rfc
+
+ if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
+ return false;
+ }
+ }
+
+ // Check the content-length if it was part of the signed data
+ if (in_array('content-length', $sig_block['headers'])) {
+ if (strlen($content) != $headers['content-length']) {
+ return false;
+ }
+ }
+
+ return true;
+
+ }
+
+ private static function fetchKey($id, $actor)
+ {
+ $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
+
+ $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
+ if (!empty($profile)) {
+ return $profile['pubkey'];
+ } elseif ($url != $actor) {
+ $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
+ if (!empty($profile)) {
+ return $profile['pubkey'];
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * @brief
+ *
+ * @param string $header
+ * @return array associate array with
+ * - \e string \b keyID
+ * - \e string \b algorithm
+ * - \e array \b headers
+ * - \e string \b signature
+ */
+ private static function parseSigHeader($header)
+ {
+ $ret = [];
+ $matches = [];
+
+ if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
+ $ret['keyId'] = $matches[1];
+ }
+
+ if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
+ $ret['algorithm'] = $matches[1];
+ }
+
+ if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
+ $ret['headers'] = explode(' ', $matches[1]);
+ }
+
+ if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
+ $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
+ }
+
+ return $ret;
+ }
+
/**
* Fetches a profile from the given url
*
$profile['name'] = defaults($data, 'name', $profile['nick']);
$profile['guid'] = defaults($data, 'uuid', null);
$profile['url'] = $data['id'];
- $profile['alias'] = self::processElement($data, 'url', 'href');
$parts = parse_url($profile['url']);
unset($parts['scheme']);
unset($parts['path']);
$profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
-
+ $profile['alias'] = self::processElement($data, 'url', 'href');
$profile['photo'] = self::processElement($data, 'icon', 'url');
+ // $profile['community']
+ // $profile['keywords']
+ // $profile['location']
$profile['about'] = defaults($data, 'summary', '');
$profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
- $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
$profile['notify'] = $data['inbox'];
$profile['poll'] = $data['outbox'];
+ $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
// Check if the address is resolvable
if (self::addrToUrl($profile['addr']) == $profile['url']) {
}
}
- // Handled
- unset($data['id']);
- unset($data['inbox']);
- unset($data['outbox']);
- unset($data['preferredUsername']);
- unset($data['name']);
- unset($data['summary']);
- unset($data['url']);
- unset($data['publicKey']);
- unset($data['endpoints']);
- unset($data['icon']);
- unset($data['uuid']);
-
+/*
// To-Do
unset($data['type']);
unset($data['manuallyApprovesFollowers']);
unset($data['isCat']); // Misskey
unset($data['kroeg:blocks']); // Kroeg
unset($data['updated']); // Kroeg
-
-/* if (!empty($data)) {
- print_r($data);
- die();
- }
*/
return $profile;
}
+ public static function processInbox($body, $header, $uid)
+ {
+ logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
+
+ if (!self::verifySignature($body, $header)) {
+ logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
+ return;
+ }
+
+ $activity = json_decode($body, true);
+
+ if (!is_array($activity)) {
+ logger('Invalid body.', LOGGER_DEBUG);
+ return;
+ }
+
+ self::processActivity($activity, $body, $uid);
+ }
+
public static function fetchOutbox($url)
{
$data = self::fetchContent($url);
}
foreach ($items as $activity) {
- self::processActivity($activity, $url);
+ self::processActivity($activity);
}
}
- function processActivity($activity, $url)
+ function processActivity($activity, $body = '', $uid = null)
{
if (empty($activity['type'])) {
+ logger('Empty type', LOGGER_DEBUG);
return;
}
if (empty($activity['object'])) {
+ logger('Empty object', LOGGER_DEBUG);
return;
}
if (empty($activity['actor'])) {
+ logger('Empty actor', LOGGER_DEBUG);
return;
+
}
$actor = self::processElement($activity, 'actor', 'id');
if (empty($actor)) {
+ logger('Empty actor - 2', LOGGER_DEBUG);
return;
}
} elseif (!empty($activity['object']['id'])) {
$object_url = $activity['object']['id'];
} else {
- return;
- }
-
- $receivers = self::getReceivers($activity);
- if (empty($receivers)) {
+ logger('No object found', LOGGER_DEBUG);
return;
}
// ----------------------------------
+/*
// unhandled
unset($activity['@context']);
unset($activity['id']);
unset($activity['context_id']);
unset($activity['statusnetConversationId']);
- $structure = $activity;
-
// To-Do?
unset($activity['context']);
unset($activity['location']);
+ unset($activity['signature']);
+*/
+ // Fetch all receivers from to, cc, bto and bcc
+ $receivers = self::getReceivers($activity);
- // handled
- unset($activity['to']);
- unset($activity['cc']);
- unset($activity['bto']);
- unset($activity['bcc']);
- unset($activity['type']);
- unset($activity['actor']);
- unset($activity['object']);
- unset($activity['published']);
- unset($activity['updated']);
- unset($activity['instrument']);
- unset($activity['inReplyTo']);
-
- if (!empty($activity)) {
- echo "Activity\n";
- print_r($activity);
- die($url."\n");
- }
-
- $activity = $structure;
- // ----------------------------------
+ // When it is a delivery to a personal inbox we add that user to the receivers
+ if (!empty($uid)) {
+ $owner = User::getOwnerDataById($uid);
+ $additional = [$owner['url'] => $uid];
+ $receivers = array_merge($receivers, $additional);
+ }
- $item = self::fetchObject($object_url, $url);
- if (empty($item)) {
- return;
+ logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
+
+ logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
+
+ // Fetch the content only on activities where this matters
+ if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
+ $item = self::fetchObject($object_url, $activity['object']);
+ if (empty($item)) {
+ logger("Object data couldn't be processed", LOGGER_DEBUG);
+ return;
+ }
+ } else {
+ if (in_array($activity['type'], ['Accept'])) {
+ $item['object'] = self::processElement($activity, 'object', 'actor', 'type', 'Follow');
+ } elseif (in_array($activity['type'], ['Undo'])) {
+ $item['object'] = self::processElement($activity, 'object', 'object', 'type', 'Follow');
+ } else {
+ $item['object'] = $object_url;
+ }
+ $item['id'] = $activity['id'];
+ $item['receiver'] = [];
+ $item['type'] = $activity['type'];
}
$item = self::addActivityFields($item, $activity);
switch ($activity['type']) {
case 'Create':
case 'Update':
- self::createItem($item);
- break;
-
case 'Announce':
- self::announceItem($item);
+ self::createItem($item, $body);
break;
case 'Like':
+ self::likeItem($item, $body);
+ break;
+
case 'Dislike':
- self::activityItem($item);
+ break;
+
+ case 'Delete':
break;
case 'Follow':
+ self::followUser($item);
+ break;
+
+ case 'Accept':
+ self::acceptFollowUser($item);
+ break;
+
+ case 'Undo':
+ self::undoFollowUser($item);
break;
default:
- echo "Unknown activity: ".$activity['type']."\n";
- print_r($item);
- die();
+ logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
break;
}
}
}
$condition = ['self' => true, 'nurl' => normalise_link($receiver)];
- $contact = DBA::selectFirst('contact', ['id'], $condition);
+ $contact = DBA::selectFirst('contact', ['uid'], $condition);
if (!DBA::isResult($contact)) {
continue;
}
- $receivers[$receiver] = $contact['id'];
+ $receivers[$receiver] = $contact['uid'];
}
}
return $receivers;
}
if (!empty($activity['instrument'])) {
- $item['service'] = self::processElement($activity, 'instrument', 'name', 'Service');
- }
-
- // Remove all "null" fields
- foreach ($item as $field => $content) {
- if (is_null($content)) {
- unset($item[$field]);
- }
+ $item['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
}
-
return $item;
}
- private static function fetchObject($object_url, $url)
+ private static function fetchObject($object_url, $object = [])
{
$data = self::fetchContent($object_url);
if (empty($data)) {
- return false;
+ $data = $object;
+ if (empty($data)) {
+ logger('Empty content', LOGGER_DEBUG);
+ return false;
+ } elseif (is_string($data)) {
+ logger('No object array provided.', LOGGER_DEBUG);
+ $item = Item::selectFirst([], ['uri' => $data]);
+ if (!DBA::isResult($item)) {
+ logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
+ return false;
+ }
+ logger('Using already stored item', LOGGER_DEBUG);
+ $data = self::createNote($item);
+ } else {
+ logger('Using provided object', LOGGER_DEBUG);
+ }
}
if (empty($data['type'])) {
+ logger('Empty type', LOGGER_DEBUG);
return false;
} else {
$type = $data['type'];
+ logger('Type ' . $type, LOGGER_DEBUG);
}
if (in_array($type, ['Note', 'Article', 'Video'])) {
- $common = self::processCommonData($data, $url);
+ $common = self::processCommonData($data);
}
switch ($type) {
case 'Note':
- return array_merge($common, self::processNote($data, $url));
+ return array_merge($common, self::processNote($data));
case 'Article':
- return array_merge($common, self::processArticle($data, $url));
+ return array_merge($common, self::processArticle($data));
case 'Video':
- return array_merge($common, self::processVideo($data, $url));
+ return array_merge($common, self::processVideo($data));
case 'Announce':
if (empty($data['object'])) {
return false;
}
- return self::fetchObject($data['object'], $url);
+ return self::fetchObject($data['object']);
case 'Person':
case 'Tombstone':
break;
default:
- echo "Unknown object type: ".$data['type']."\n";
- print_r($data);
- die($url."\n");
+ logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
break;
}
}
- private static function processCommonData(&$object, $url)
+ private static function processCommonData(&$object)
{
if (empty($object['id']) || empty($object['attributedTo'])) {
return false;
}
$item = [];
+ $item['type'] = $object['type'];
$item['uri'] = $object['id'];
if (!empty($object['inReplyTo'])) {
$item['context'] = defaults($object, 'context', null);
$item['conversation'] = defaults($object, 'conversation', null);
$item['sensitive'] = defaults($object, 'sensitive', null);
- $item['name'] = defaults($object, 'name', null);
- $item['title'] = defaults($object, 'title', null);
- $item['content'] = defaults($object, 'content', null);
+ $item['name'] = defaults($object, 'title', null);
+ $item['name'] = defaults($object, 'name', $item['name']);
$item['summary'] = defaults($object, 'summary', null);
- $item['location'] = self::processElement($object, 'location', 'name', 'Place');
+ $item['content'] = defaults($object, 'content', null);
+ $item['source'] = defaults($object, 'source', null);
+ $item['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
$item['attachments'] = defaults($object, 'attachment', null);
$item['tags'] = defaults($object, 'tag', null);
- $item['service'] = self::processElement($object, 'instrument', 'name', 'Service');
+ $item['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
$item['alternate-url'] = self::processElement($object, 'url', 'href');
$item['receiver'] = self::getReceivers($object);
- // handled
- unset($object['id']);
- unset($object['inReplyTo']);
- unset($object['published']);
- unset($object['updated']);
- unset($object['uuid']);
- unset($object['attributedTo']);
- unset($object['context']);
- unset($object['conversation']);
- unset($object['sensitive']);
- unset($object['name']);
- unset($object['title']);
- unset($object['content']);
- unset($object['summary']);
- unset($object['location']);
- unset($object['attachment']);
- unset($object['tag']);
- unset($object['instrument']);
- unset($object['url']);
- unset($object['to']);
- unset($object['cc']);
- unset($object['bto']);
- unset($object['bcc']);
-
+/*
// To-Do
unset($object['source']);
unset($object['replies']);
unset($object['icon']);
- /*
+ // Also missing:
audience, preview, endTime, startTime, generator, image
- */
-
+*/
return $item;
}
- private static function processNote($object, $url)
+ private static function processNote($object)
{
$item = [];
+/*
// To-Do?
unset($object['emoji']);
unset($object['atomUri']);
unset($object['shares']);
unset($object['quoteUrl']);
unset($object['statusnetConversationId']);
-
- if (empty($object))
- return $item;
-
- echo "Unknown Note\n";
- print_r($object);
- print_r($item);
- die($url."\n");
-
- return [];
+*/
+ return $item;
}
- private static function processArticle($object, $url)
+ private static function processArticle($object)
{
$item = [];
- if (empty($object))
- return $item;
-
- echo "Unknown Article\n";
- print_r($object);
- print_r($item);
- die($url."\n");
-
- return [];
+ return $item;
}
- private static function processVideo($object, $url)
+ private static function processVideo($object)
{
$item = [];
-
+/*
// To-Do?
unset($object['category']);
unset($object['licence']);
unset($object['dislikes']);
unset($object['shares']);
unset($object['comments']);
-
- if (empty($object))
- return $item;
-
- echo "Unknown Video\n";
- print_r($object);
- print_r($item);
- die($url."\n");
-
- return [];
+*/
+ return $item;
}
- private static function processElement($array, $element, $key, $type = null)
+ private static function processElement($array, $element, $key, $type = null, $type_value = null)
{
if (empty($array)) {
return false;
return $array[$element];
}
- if (is_null($type)) {
+ if (is_null($type_value)) {
if (!empty($array[$element][$key])) {
return $array[$element][$key];
}
return false;
}
- if (!empty($array[$element][$key]) && !empty($array[$element]['type']) && ($array[$element]['type'] == $type)) {
+ if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
return $array[$element][$key];
}
return false;
}
- private static function createItem($item)
+ private static function convertMentions($body)
{
-// print_r($item);
+ $URLSearchString = "^\[\]";
+ $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
+
+ return $body;
}
- private static function announceItem($item)
+ private static function constructTagList($tags, $sensitive)
{
-// print_r($item);
+ if (empty($tags)) {
+ return '';
+ }
+
+ $tag_text = '';
+ foreach ($tags as $tag) {
+ if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
+ if (!empty($tag_text)) {
+ $tag_text .= ',';
+ }
+
+ $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
+ }
+ }
+
+ /// @todo add nsfw for $sensitive
+
+ return $tag_text;
}
- private static function activityItem($item)
+ private static function constructAttachList($attachments, $item)
{
- // print_r($item);
+ if (empty($attachments)) {
+ return $item;
+ }
+
+ foreach ($attachments as $attach) {
+ $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
+ if ($filetype == 'image') {
+ $item['body'] .= "\n[img]".$attach['url'].'[/img]';
+ } else {
+ if (!empty($item["attach"])) {
+ $item["attach"] .= ',';
+ } else {
+ $item["attach"] = '';
+ }
+ if (!isset($attach['length'])) {
+ $attach['length'] = "0";
+ }
+ $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
+ }
+ }
+
+ return $item;
}
+ private static function createItem($activity, $body)
+ {
+ $item = [];
+ $item['verb'] = ACTIVITY_POST;
+ $item['parent-uri'] = $activity['reply-to-uri'];
+
+ if ($activity['reply-to-uri'] == $activity['uri']) {
+ $item['gravity'] = GRAVITY_PARENT;
+ $item['object-type'] = ACTIVITY_OBJ_NOTE;
+ } else {
+ $item['gravity'] = GRAVITY_COMMENT;
+ $item['object-type'] = ACTIVITY_OBJ_COMMENT;
+ }
+
+ self::postItem($activity, $item, $body);
+ }
+
+ private static function likeItem($activity, $body)
+ {
+ $item = [];
+ $item['verb'] = ACTIVITY_LIKE;
+ $item['parent-uri'] = $activity['object'];
+ $item['gravity'] = GRAVITY_ACTIVITY;
+ $item['object-type'] = ACTIVITY_OBJ_NOTE;
+
+ self::postItem($activity, $item, $body);
+ }
+
+ private static function postItem($activity, $item, $body)
+ {
+ /// @todo What to do with $activity['context']?
+
+ $item['network'] = Protocol::ACTIVITYPUB;
+ $item['private'] = !in_array(0, $activity['receiver']);
+ $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
+ $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
+ $item['uri'] = $activity['uri'];
+ $item['created'] = $activity['published'];
+ $item['edited'] = $activity['updated'];
+ $item['guid'] = $activity['uuid'];
+ $item['title'] = HTML::toBBCode($activity['name']);
+ $item['content-warning'] = HTML::toBBCode($activity['summary']);
+ $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
+ $item['location'] = $activity['location'];
+ $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
+ $item['app'] = $activity['service'];
+ $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
+
+ $item = self::constructAttachList($activity['attachments'], $item);
+
+ $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
+ if (!empty($source)) {
+ $item['body'] = $source;
+ }
+
+ $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
+ $item['source'] = $body;
+ $item['conversation-uri'] = $activity['conversation'];
+
+ foreach ($activity['receiver'] as $receiver) {
+ $item['uid'] = $receiver;
+ $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
+
+ if (($receiver != 0) && empty($item['contact-id'])) {
+ $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
+ }
+
+ $item_id = Item::insert($item);
+ logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
+ if (!empty($item_id) && ($item['uid'] == 0)) {
+ Item::distribute($item_id);
+ }
+ }
+ }
+
+ private static function followUser($activity)
+ {
+ if (empty($activity['receiver'][$activity['object']])) {
+ return;
+ }
+
+ $uid = $activity['receiver'][$activity['object']];
+ $owner = User::getOwnerDataById($uid);
+
+ $cid = Contact::getIdForURL($activity['owner'], $uid);
+ if (!empty($cid)) {
+ $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
+ } else {
+ $contact = false;
+ }
+
+ $item = ['author-id' => Contact::getIdForURL($activity['owner'])];
+
+ Contact::addRelationship($owner, $contact, $item);
+
+ $cid = Contact::getIdForURL($activity['owner'], $uid);
+ if (empty($cid)) {
+ return;
+ }
+
+ $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
+ if ($contact['network'] != Protocol::ACTIVITYPUB) {
+ Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
+ }
+
+ DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
+ logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
+ }
+
+ private static function acceptFollowUser($activity)
+ {
+ if (empty($activity['receiver'][$activity['object']])) {
+ return;
+ }
+
+ $uid = $activity['receiver'][$activity['object']];
+ $owner = User::getOwnerDataById($uid);
+
+ $cid = Contact::getIdForURL($activity['owner'], $uid);
+ if (empty($cid)) {
+ logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
+ return;
+ }
+
+ $fields = ['pending' => false];
+ $condition = ['id' => $cid, 'pending' => true];
+ DBA::update('comtact', $fields, $condition);
+ logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
+ }
+
+ private static function undoFollowUser($activity)
+ {
+ if (empty($activity['receiver'][$activity['object']])) {
+ return;
+ }
+
+ $uid = $activity['receiver'][$activity['object']];
+ $owner = User::getOwnerDataById($uid);
+
+ $cid = Contact::getIdForURL($activity['owner'], $uid);
+ if (empty($cid)) {
+ logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
+ return;
+ }
+
+ $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
+ if (!DBA::isResult($contact)) {
+ return;
+ }
+
+ Contact::removeFollower($owner, $contact);
+ logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
+ }
}