3 * @file src/Protocol/ActivityPub.php
5 namespace Friendica\Protocol;
7 use Friendica\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
10 use Friendica\Util\Network;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Crypto;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Content\Text\HTML;
22 use Friendica\Util\JsonLD;
23 use Friendica\Util\LDSignature;
26 * @brief ActivityPub Protocol class
27 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
28 * https://www.w3.org/TR/activitypub/
29 * https://www.w3.org/TR/activitystreams-core/
30 * https://www.w3.org/TR/activitystreams-vocabulary/
32 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
33 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
35 * Digest: https://tools.ietf.org/html/rfc5843
36 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
37 * https://github.com/digitalbazaar/php-json-ld
39 * Part of the code for HTTP signing is taken from the Osada project.
40 * https://framagit.org/macgirvin/osada
45 * - Activities: Dislike, Update, Delete
46 * - Object Types: Person, Tombstome
49 * - Activities: Like, Dislike, Update, Delete, Announce
50 * - Object Tyoes: Article, Person, Tombstone
53 * - Endpoints: Outbox, Follower, Following
55 * - Queueing unsucessful deliveries
59 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
61 public static function isRequest()
63 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
64 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
68 * Return the ActivityPub profile of the given user
70 * @param integer $uid User ID
73 public static function profile($uid)
75 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
76 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
77 'account_removed' => false, 'verified' => true];
78 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
79 $user = DBA::selectFirst('user', $fields, $condition);
80 if (!DBA::isResult($user)) {
84 $fields = ['locality', 'region', 'country-name'];
85 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
86 if (!DBA::isResult($profile)) {
90 $fields = ['name', 'url', 'location', 'about', 'avatar'];
91 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
92 if (!DBA::isResult($contact)) {
96 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
97 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
98 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
100 $data['id'] = $contact['url'];
101 $data['uuid'] = $user['guid'];
102 $data['type'] = $accounttype[$user['account-type']];
103 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
104 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
105 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
106 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
107 $data['preferredUsername'] = $user['nickname'];
108 $data['name'] = $contact['name'];
109 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
110 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
111 $data['summary'] = $contact['about'];
112 $data['url'] = $contact['url'];
113 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
114 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
115 'owner' => $contact['url'],
116 'publicKeyPem' => $user['pubkey']];
117 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
118 $data['icon'] = ['type' => 'Image',
119 'url' => $contact['avatar']];
121 // tags: https://kitty.town/@inmysocks/100656097926961126.json
125 private static function fetchPermissionBlockFromConversation($item)
127 if (empty($item['thr-parent'])) {
131 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
132 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
133 if (!DBA::isResult($conversation)) {
137 $activity = json_decode($conversation['source'], true);
139 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
140 $profile = ActivityPub::fetchprofile($actor);
142 $item_profile = ActivityPub::fetchprofile($item['owner-link']);
146 $elements = ['to', 'cc', 'bto', 'bcc'];
147 foreach ($elements as $element) {
148 if (empty($activity[$element])) {
151 if (is_string($activity[$element])) {
152 $activity[$element] = [$activity[$element]];
154 foreach ($activity[$element] as $receiver) {
155 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
156 $receiver = $item_profile['followers'];
158 if ($receiver != $item['owner-link']) {
159 $permissions[$element][] = $receiver;
166 public static function createPermissionBlockForItem($item)
168 $data = ['to' => [], 'cc' => []];
170 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
172 $actor_profile = ActivityPub::fetchprofile($item['author-link']);
174 $terms = Term::tagArrayFromItemId($item['id']);
176 $contacts[$item['author-link']] = $item['author-link'];
178 if (!$item['private']) {
179 $data['to'][] = self::PUBLIC;
180 if (!empty($actor_profile['followers'])) {
181 $data['cc'][] = $actor_profile['followers'];
184 foreach ($terms as $term) {
185 if ($term['type'] != TERM_MENTION) {
188 $profile = self::fetchprofile($term['url']);
189 if (!empty($profile) && empty($contacts[$profile['url']])) {
190 $data['cc'][] = $profile['url'];
191 $contacts[$profile['url']] = $profile['url'];
195 $receiver_list = Item::enumeratePermissions($item);
199 foreach ($terms as $term) {
200 if ($term['type'] != TERM_MENTION) {
203 $cid = Contact::getIdForURL($term['url'], $item['uid']);
204 if (!empty($cid) && in_array($cid, $receiver_list)) {
205 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
206 $data['to'][] = $contact['url'];
207 $contacts[$contact['url']] = $contact['url'];
211 foreach ($receiver_list as $receiver) {
212 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
213 if (empty($contacts[$contact['url']])) {
214 $data['cc'][] = $contact['url'];
215 $contacts[$contact['url']] = $contact['url'];
220 $parents = Item::select(['author-link', 'owner-link'], ['parent' => $item['parent']]);
221 while ($parent = Item::fetch($parents)) {
222 $profile = self::fetchprofile($parent['author-link']);
223 if (!empty($profile) && empty($contacts[$profile['url']])) {
224 $data['cc'][] = $profile['url'];
225 $contacts[$profile['url']] = $profile['url'];
228 $profile = self::fetchprofile($parent['owner-link']);
229 if (!empty($profile) && empty($contacts[$profile['url']])) {
230 $data['cc'][] = $profile['url'];
231 $contacts[$profile['url']] = $profile['url'];
234 DBA::close($parents);
236 if (empty($data['to'])) {
237 $data['to'] = $data['cc'];
244 public static function fetchTargetInboxes($item, $uid)
246 $permissions = self::createPermissionBlockForItem($item);
247 if (empty($permissions)) {
253 $item_profile = ActivityPub::fetchprofile($item['owner-link']);
255 $elements = ['to', 'cc', 'bto', 'bcc'];
256 foreach ($elements as $element) {
257 if (empty($permissions[$element])) {
260 foreach ($permissions[$element] as $receiver) {
261 if ($receiver == $item_profile['followers']) {
262 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
263 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
264 while ($contact = DBA::fetch($contacts)) {
265 $contact = defaults($contact, 'batch', $contact['notify']);
266 $inboxes[$contact] = $contact;
268 DBA::close($contacts);
270 $profile = self::fetchprofile($receiver);
271 if (!empty($profile)) {
272 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
273 $inboxes[$target] = $target;
279 if (!empty($item_profile['sharedinbox'])) {
280 unset($inboxes[$item_profile['sharedinbox']]);
283 if (!empty($item_profile['inbox'])) {
284 unset($inboxes[$item_profile['inbox']]);
290 public static function createActivityFromItem($item_id)
292 $item = Item::selectFirst([], ['id' => $item_id]);
294 if (!DBA::isResult($item)) {
298 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
299 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
300 if (DBA::isResult($conversation)) {
301 $data = json_decode($conversation['source']);
307 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
308 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
309 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
310 'conversation' => 'ostatus:conversation',
311 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
313 $data['id'] = $item['uri'] . '#activity';
314 $data['type'] = 'Create';
315 $data['actor'] = $item['author-link'];
317 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
319 if ($item["created"] != $item["edited"]) {
320 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
323 $data['context_id'] = $item['parent'];
324 $data['context'] = self::createConversationURLFromItem($item);
326 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
328 $data['object'] = self::createObjectTypeFromItem($item);
330 $owner = User::getOwnerDataById($item['uid']);
332 return LDSignature::sign($data, $owner);
335 public static function createObjectFromItemID($item_id)
337 $item = Item::selectFirst([], ['id' => $item_id]);
339 if (!DBA::isResult($item)) {
343 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
344 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
345 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
346 'conversation' => 'ostatus:conversation',
347 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
349 $data = array_merge($data, self::createObjectTypeFromItem($item));
355 private static function createTagList($item)
359 $terms = Term::tagArrayFromItemId($item['id']);
360 foreach ($terms as $term) {
361 if ($term['type'] == TERM_MENTION) {
362 $contact = Contact::getDetailsByURL($term['url']);
363 if (!empty($contact['addr'])) {
364 $mention = '@' . $contact['addr'];
366 $mention = '@' . $term['url'];
369 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
375 private static function createConversationURLFromItem($item)
377 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
378 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
379 $conversation_uri = $conversation['conversation-uri'];
381 $conversation_uri = $item['parent-uri'];
383 return $conversation_uri;
386 private static function createObjectTypeFromItem($item)
388 if (!empty($item['title'])) {
395 $data['id'] = $item['uri'];
396 $data['type'] = $type;
397 $data['summary'] = null; // Ignore by now
399 if ($item['uri'] != $item['thr-parent']) {
400 $data['inReplyTo'] = $item['thr-parent'];
402 $data['inReplyTo'] = null;
405 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
407 if ($item["created"] != $item["edited"]) {
408 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
411 $data['url'] = $item['plink'];
412 $data['attributedTo'] = $item['author-link'];
413 $data['actor'] = $item['author-link'];
414 $data['sensitive'] = false; // - Query NSFW
415 $data['context_id'] = $item['parent'];
416 $data['conversation'] = $data['context'] = self::createConversationURLFromItem($item);
418 if (!empty($item['title'])) {
419 $data['name'] = BBCode::convert($item['title'], false, 7);
422 $data['content'] = BBCode::convert($item['body'], false, 7);
423 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
424 $data['attachment'] = []; // @ToDo
425 $data['tag'] = self::createTagList($item);
426 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
428 //$data['emoji'] = []; // Ignore by now
432 public static function transmitActivity($activity, $target, $uid)
434 $profile = self::fetchprofile($target);
436 $owner = User::getOwnerDataById($uid);
438 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
439 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
441 'actor' => $owner['url'],
442 'object' => $profile['url'],
443 'to' => $profile['url']];
445 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
447 $signed = LDSignature::sign($data, $owner);
448 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
451 public static function transmitContactAccept($target, $id, $uid)
453 $profile = self::fetchprofile($target);
455 $owner = User::getOwnerDataById($uid);
456 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
457 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
459 'actor' => $owner['url'],
460 'object' => ['id' => $id, 'type' => 'Follow',
461 'actor' => $profile['url'],
462 'object' => $owner['url']],
463 'to' => $profile['url']];
465 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
467 $signed = LDSignature::sign($data, $owner);
468 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
471 public static function transmitContactReject($target, $id, $uid)
473 $profile = self::fetchprofile($target);
475 $owner = User::getOwnerDataById($uid);
476 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
477 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
479 'actor' => $owner['url'],
480 'object' => ['id' => $id, 'type' => 'Follow',
481 'actor' => $profile['url'],
482 'object' => $owner['url']],
483 'to' => $profile['url']];
485 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
487 $signed = LDSignature::sign($data, $owner);
488 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
491 public static function transmitContactUndo($target, $uid)
493 $profile = self::fetchprofile($target);
495 $id = System::baseUrl() . '/activity/' . System::createGUID();
497 $owner = User::getOwnerDataById($uid);
498 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
501 'actor' => $owner['url'],
502 'object' => ['id' => $id, 'type' => 'Follow',
503 'actor' => $owner['url'],
504 'object' => $profile['url']],
505 'to' => $profile['url']];
507 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
509 $signed = LDSignature::sign($data, $owner);
510 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
514 * Fetches ActivityPub content from the given url
516 * @param string $url content url
519 public static function fetchContent($url)
521 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
522 if (!$ret['success'] || empty($ret['body'])) {
526 return json_decode($ret['body'], true);
530 * Resolves the profile url from the address by using webfinger
532 * @param string $addr profile address (user@domain.tld)
535 private static function addrToUrl($addr)
537 $addr_parts = explode('@', $addr);
538 if (count($addr_parts) != 2) {
542 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
544 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
545 if (!$ret['success'] || empty($ret['body'])) {
549 $data = json_decode($ret['body'], true);
551 if (empty($data['links'])) {
555 foreach ($data['links'] as $link) {
556 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
560 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
561 return $link['href'];
568 public static function fetchprofile($url, $update = false)
575 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
576 if (DBA::isResult($apcontact)) {
580 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
581 if (DBA::isResult($apcontact)) {
585 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
586 if (DBA::isResult($apcontact)) {
591 if (empty(parse_url($url, PHP_URL_SCHEME))) {
592 $url = self::addrToUrl($url);
598 $data = self::fetchContent($url);
600 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
605 $apcontact['url'] = $data['id'];
606 $apcontact['uuid'] = defaults($data, 'uuid', null);
607 $apcontact['type'] = defaults($data, 'type', null);
608 $apcontact['following'] = defaults($data, 'following', null);
609 $apcontact['followers'] = defaults($data, 'followers', null);
610 $apcontact['inbox'] = defaults($data, 'inbox', null);
611 $apcontact['outbox'] = defaults($data, 'outbox', null);
612 $apcontact['sharedinbox'] = JsonLD::fetchElement($data, 'endpoints', 'sharedInbox');
613 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
614 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
615 $apcontact['about'] = defaults($data, 'summary', '');
616 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon', 'url');
617 $apcontact['alias'] = JsonLD::fetchElement($data, 'url', 'href');
619 $parts = parse_url($apcontact['url']);
620 unset($parts['scheme']);
621 unset($parts['path']);
622 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
624 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data, 'publicKey', 'publicKeyPem'));
627 // manuallyApprovesFollowers
630 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
632 // Unhandled from Misskey
633 // sharedInbox, isCat
635 // Unhandled from Kroeg
636 // kroeg:blocks, updated
638 // Check if the address is resolvable
639 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
640 $parts = parse_url($apcontact['url']);
641 unset($parts['path']);
642 $apcontact['baseurl'] = Network::unparseURL($parts);
644 $apcontact['addr'] = null;
647 if ($apcontact['url'] == $apcontact['alias']) {
648 $apcontact['alias'] = null;
651 $apcontact['updated'] = DateTimeFormat::utcNow();
653 DBA::update('apcontact', $apcontact, ['url' => $url], true);
659 * Fetches a profile from the given url into an array that is compatible to Probe::uri
661 * @param string $url profile url
664 public static function probeProfile($url)
666 $apcontact = self::fetchprofile($url, true);
667 if (empty($apcontact)) {
671 $profile = ['network' => Protocol::ACTIVITYPUB];
672 $profile['nick'] = $apcontact['nick'];
673 $profile['name'] = $apcontact['name'];
674 $profile['guid'] = $apcontact['uuid'];
675 $profile['url'] = $apcontact['url'];
676 $profile['addr'] = $apcontact['addr'];
677 $profile['alias'] = $apcontact['alias'];
678 $profile['photo'] = $apcontact['photo'];
679 // $profile['community']
680 // $profile['keywords']
681 // $profile['location']
682 $profile['about'] = $apcontact['about'];
683 $profile['batch'] = $apcontact['sharedinbox'];
684 $profile['notify'] = $apcontact['inbox'];
685 $profile['poll'] = $apcontact['outbox'];
686 $profile['pubkey'] = $apcontact['pubkey'];
687 $profile['baseurl'] = $apcontact['baseurl'];
689 // Remove all "null" fields
690 foreach ($profile as $field => $content) {
691 if (is_null($content)) {
692 unset($profile[$field]);
699 public static function processInbox($body, $header, $uid)
701 $http_signer = HTTPSignature::getSigner($body, $header);
702 if (empty($http_signer)) {
703 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
706 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
709 $activity = json_decode($body, true);
711 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
712 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
714 if (empty($activity)) {
715 logger('Invalid body.', LOGGER_DEBUG);
719 if (LDSignature::isSigned($activity)) {
720 $ld_signer = LDSignature::getSigner($activity);
721 if (!empty($ld_signer && ($actor == $http_signer))) {
722 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
723 $trust_source = true;
724 } elseif (!empty($ld_signer)) {
725 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
726 $trust_source = true;
727 } elseif ($actor == $http_signer) {
728 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
729 $trust_source = true;
731 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
732 $trust_source = false;
734 } elseif ($actor == $http_signer) {
735 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
736 $trust_source = true;
738 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
739 $trust_source = false;
742 self::processActivity($activity, $body, $uid, $trust_source);
745 public static function fetchOutbox($url, $uid)
747 $data = self::fetchContent($url);
752 if (!empty($data['orderedItems'])) {
753 $items = $data['orderedItems'];
754 } elseif (!empty($data['first']['orderedItems'])) {
755 $items = $data['first']['orderedItems'];
756 } elseif (!empty($data['first'])) {
757 self::fetchOutbox($data['first'], $uid);
763 foreach ($items as $activity) {
764 self::processActivity($activity, '', $uid, true);
768 private static function prepareObjectData($activity, $uid, $trust_source)
770 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
772 logger('Empty actor', LOGGER_DEBUG);
776 // Fetch all receivers from to, cc, bto and bcc
777 $receivers = self::getReceivers($activity, $actor);
779 // When it is a delivery to a personal inbox we add that user to the receivers
781 $owner = User::getOwnerDataById($uid);
782 $additional = ['uid:' . $uid => $uid];
783 $receivers = array_merge($receivers, $additional);
786 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
788 if (is_string($activity['object'])) {
789 $object_url = $activity['object'];
790 } elseif (!empty($activity['object']['id'])) {
791 $object_url = $activity['object']['id'];
793 logger('No object found', LOGGER_DEBUG);
797 // Fetch the content only on activities where this matters
798 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
799 $object_data = self::fetchObject($object_url, $activity['object'], $trust_source);
800 if (empty($object_data)) {
801 logger("Object data couldn't be processed", LOGGER_DEBUG);
804 } elseif ($activity['type'] == 'Accept') {
806 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
807 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'actor');
808 } elseif ($activity['type'] == 'Undo') {
810 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
811 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'object');
812 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
813 // Create a mostly empty array out of the activity data (instead of the object).
814 // This way we later don't have to check for the existence of ech individual array element.
815 $object_data = self::processCommonData($activity);
816 $object_data['name'] = $activity['type'];
817 $object_data['author'] = $activity['actor'];
818 $object_data['object'] = $object_url;
819 } elseif ($activity['type'] == 'Follow') {
820 $object_data['id'] = $activity['id'];
821 $object_data['object'] = $object_url;
826 $object_data = self::addActivityFields($object_data, $activity);
828 $object_data['type'] = $activity['type'];
829 $object_data['owner'] = $actor;
830 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
835 private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
837 if (empty($activity['type'])) {
838 logger('Empty type', LOGGER_DEBUG);
842 if (empty($activity['object'])) {
843 logger('Empty object', LOGGER_DEBUG);
847 if (empty($activity['actor'])) {
848 logger('Empty actor', LOGGER_DEBUG);
854 // title, atomUri, context_id, statusnetConversationId
857 // context, location, signature;
859 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
861 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
862 if (empty($object_data)) {
863 logger('No object data found', LOGGER_DEBUG);
867 switch ($activity['type']) {
870 self::createItem($object_data, $body);
874 self::likeItem($object_data, $body);
887 self::followUser($object_data);
891 if ($object_data['object_type'] == 'Follow') {
892 self::acceptFollowUser($object_data);
897 if ($object_data['object_type'] == 'Follow') {
898 self::undoFollowUser($object_data);
903 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
908 private static function getReceivers($activity, $actor)
912 // When it is an answer, we inherite the receivers from the parent
913 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
914 if (!empty($replyto)) {
915 $parents = Item::select(['uid'], ['uri' => $replyto]);
916 while ($parent = Item::fetch($parents)) {
917 $receivers['uid:' . $parent['uid']] = $parent['uid'];
921 if (!empty($actor)) {
922 $profile = self::fetchprofile($actor);
923 $followers = defaults($profile, 'followers', '');
925 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
927 logger('Empty actor', LOGGER_DEBUG);
931 $elements = ['to', 'cc', 'bto', 'bcc'];
932 foreach ($elements as $element) {
933 if (empty($activity[$element])) {
937 // The receiver can be an arror or a string
938 if (is_string($activity[$element])) {
939 $activity[$element] = [$activity[$element]];
942 foreach ($activity[$element] as $receiver) {
943 if ($receiver == self::PUBLIC) {
944 $receivers['uid:0'] = 0;
947 if (($receiver == self::PUBLIC) && !empty($actor)) {
948 // This will most likely catch all OStatus connections to Mastodon
949 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
950 $contacts = DBA::select('contact', ['uid'], $condition);
951 while ($contact = DBA::fetch($contacts)) {
952 if ($contact['uid'] != 0) {
953 $receivers['uid:' . $contact['uid']] = $contact['uid'];
956 DBA::close($contacts);
959 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
960 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
961 'network' => Protocol::ACTIVITYPUB];
962 $contacts = DBA::select('contact', ['uid'], $condition);
963 while ($contact = DBA::fetch($contacts)) {
964 if ($contact['uid'] != 0) {
965 $receivers['uid:' . $contact['uid']] = $contact['uid'];
968 DBA::close($contacts);
972 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
973 $contact = DBA::selectFirst('contact', ['uid'], $condition);
974 if (!DBA::isResult($contact)) {
977 $receivers['uid:' . $contact['uid']] = $contact['uid'];
983 private static function addActivityFields($object_data, $activity)
985 if (!empty($activity['published']) && empty($object_data['published'])) {
986 $object_data['published'] = $activity['published'];
989 if (!empty($activity['updated']) && empty($object_data['updated'])) {
990 $object_data['updated'] = $activity['updated'];
993 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
994 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
997 if (!empty($activity['instrument'])) {
998 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1000 return $object_data;
1003 private static function fetchObject($object_url, $object = [], $trust_source = false)
1005 if (!$trust_source || is_string($object)) {
1006 $data = self::fetchContent($object_url);
1008 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1009 $data = $object_url;
1011 logger('Fetched content for ' . $object_url, LOGGER_DEBUG);
1014 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1018 if (is_string($data)) {
1019 $item = Item::selectFirst([], ['uri' => $data]);
1020 if (!DBA::isResult($item)) {
1021 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1024 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1025 $data = self::createObjectTypeFromItem($item);
1028 if (empty($data['type'])) {
1029 logger('Empty type', LOGGER_DEBUG);
1032 $type = $data['type'];
1033 logger('Type ' . $type, LOGGER_DEBUG);
1036 if (in_array($type, ['Note', 'Article', 'Video'])) {
1037 $common = self::processCommonData($data);
1042 return array_merge($common, self::processNote($data));
1044 return array_merge($common, self::processArticle($data));
1046 return array_merge($common, self::processVideo($data));
1049 if (empty($data['object'])) {
1052 return self::fetchObject($data['object']);
1059 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1064 private static function processCommonData(&$object)
1066 if (empty($object['id'])) {
1071 $object_data['type'] = $object['type'];
1072 $object_data['uri'] = $object['id'];
1074 if (!empty($object['inReplyTo'])) {
1075 $object_data['reply-to-uri'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1077 $object_data['reply-to-uri'] = $object_data['uri'];
1080 $object_data['published'] = defaults($object, 'published', null);
1081 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1083 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1084 $object_data['published'] = $object_data['updated'];
1087 $object_data['uuid'] = defaults($object, 'uuid', null);
1088 $object_data['owner'] = $object_data['author'] = JsonLD::fetchElement($object, 'attributedTo', 'id');
1089 $object_data['context'] = defaults($object, 'context', null);
1090 $object_data['conversation'] = defaults($object, 'conversation', null);
1091 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1092 $object_data['name'] = defaults($object, 'title', null);
1093 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1094 $object_data['summary'] = defaults($object, 'summary', null);
1095 $object_data['content'] = defaults($object, 'content', null);
1096 $object_data['source'] = defaults($object, 'source', null);
1097 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1098 $object_data['attachments'] = defaults($object, 'attachment', null);
1099 $object_data['tags'] = defaults($object, 'tag', null);
1100 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1101 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1102 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1105 // @context, type, actor, signature, mediaType, duration, replies, icon
1107 // Also missing: (Defined in the standard, but currently unused)
1108 // audience, preview, endTime, startTime, generator, image
1110 return $object_data;
1113 private static function processNote($object)
1118 // emoji, atomUri, inReplyToAtomUri
1121 // contentMap, announcement_count, announcements, context_id, likes, like_count
1122 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1124 return $object_data;
1127 private static function processArticle($object)
1131 return $object_data;
1134 private static function processVideo($object)
1139 // category, licence, language, commentsEnabled
1142 // views, waitTranscoding, state, support, subtitleLanguage
1143 // likes, dislikes, shares, comments
1145 return $object_data;
1148 private static function convertMentions($body)
1150 $URLSearchString = "^\[\]";
1151 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1156 private static function constructTagList($tags, $sensitive)
1163 foreach ($tags as $tag) {
1164 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1165 if (!empty($tag_text)) {
1169 if (empty($tag['href'])) {
1174 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1178 /// @todo add nsfw for $sensitive
1183 private static function constructAttachList($attachments, $item)
1185 if (empty($attachments)) {
1189 foreach ($attachments as $attach) {
1190 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1191 if ($filetype == 'image') {
1192 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1194 if (!empty($item["attach"])) {
1195 $item["attach"] .= ',';
1197 $item["attach"] = '';
1199 if (!isset($attach['length'])) {
1200 $attach['length'] = "0";
1202 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1209 private static function createItem($activity, $body)
1212 $item['verb'] = ACTIVITY_POST;
1213 $item['parent-uri'] = $activity['reply-to-uri'];
1215 if ($activity['reply-to-uri'] == $activity['uri']) {
1216 $item['gravity'] = GRAVITY_PARENT;
1217 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1219 $item['gravity'] = GRAVITY_COMMENT;
1220 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1223 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1224 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1225 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1228 self::postItem($activity, $item, $body);
1231 private static function likeItem($activity, $body)
1234 $item['verb'] = ACTIVITY_LIKE;
1235 $item['parent-uri'] = $activity['object'];
1236 $item['gravity'] = GRAVITY_ACTIVITY;
1237 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1239 self::postItem($activity, $item, $body);
1242 private static function postItem($activity, $item, $body)
1244 /// @todo What to do with $activity['context']?
1246 $item['network'] = Protocol::ACTIVITYPUB;
1247 $item['private'] = !in_array(0, $activity['receiver']);
1248 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1249 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1250 $item['uri'] = $activity['uri'];
1251 $item['created'] = $activity['published'];
1252 $item['edited'] = $activity['updated'];
1253 $item['guid'] = $activity['uuid'];
1254 $item['title'] = HTML::toBBCode($activity['name']);
1255 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1256 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1257 $item['location'] = $activity['location'];
1258 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1259 $item['app'] = $activity['service'];
1260 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1262 $item = self::constructAttachList($activity['attachments'], $item);
1264 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1265 if (!empty($source)) {
1266 $item['body'] = $source;
1269 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1270 $item['source'] = $body;
1271 $item['conversation-uri'] = $activity['conversation'];
1273 foreach ($activity['receiver'] as $receiver) {
1274 $item['uid'] = $receiver;
1275 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1277 if (($receiver != 0) && empty($item['contact-id'])) {
1278 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1281 $item_id = Item::insert($item);
1282 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1286 private static function fetchMissingActivity($url, $child)
1288 $object = ActivityPub::fetchContent($url);
1289 if (empty($object)) {
1290 logger('Activity ' . $url . ' was not fetchable, aborting.');
1295 $activity['@context'] = $object['@context'];
1296 unset($object['@context']);
1297 $activity['id'] = $object['id'];
1298 $activity['to'] = defaults($object, 'to', []);
1299 $activity['cc'] = defaults($object, 'cc', []);
1300 $activity['actor'] = $child['author'];
1301 $activity['object'] = $object;
1302 $activity['published'] = $object['published'];
1303 $activity['type'] = 'Create';
1305 self::processActivity($activity);
1306 logger('Activity ' . $url . ' had been fetched and processed.');
1309 private static function getUserOfObject($object)
1311 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1312 if (!DBA::isResult($self)) {
1315 return $self['uid'];
1319 private static function followUser($activity)
1321 $uid = self::getUserOfObject($activity['object']);
1326 $owner = User::getOwnerDataById($uid);
1328 $cid = Contact::getIdForURL($activity['owner'], $uid);
1330 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1335 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1336 'author-link' => $activity['owner']];
1338 Contact::addRelationship($owner, $contact, $item);
1339 $cid = Contact::getIdForURL($activity['owner'], $uid);
1344 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1345 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1346 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1349 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1350 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1353 private static function acceptFollowUser($activity)
1355 $uid = self::getUserOfObject($activity['object']);
1360 $owner = User::getOwnerDataById($uid);
1362 $cid = Contact::getIdForURL($activity['owner'], $uid);
1364 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1368 $fields = ['pending' => false];
1370 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1371 if ($contact['rel'] == Contact::FOLLOWER) {
1372 $fields['rel'] = Contact::FRIEND;
1375 $condition = ['id' => $cid];
1376 DBA::update('contact', $fields, $condition);
1377 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1380 private static function undoFollowUser($activity)
1382 $uid = self::getUserOfObject($activity['object']);
1387 $owner = User::getOwnerDataById($uid);
1389 $cid = Contact::getIdForURL($activity['owner'], $uid);
1391 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1395 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1396 if (!DBA::isResult($contact)) {
1400 Contact::removeFollower($owner, $contact);
1401 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);