3 * @file src/Protocol/ActivityPub/Receiver.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Util\HTTPSignature;
9 use Friendica\Core\Protocol;
10 use Friendica\Model\Contact;
11 use Friendica\Model\APContact;
12 use Friendica\Model\Item;
13 use Friendica\Model\User;
14 use Friendica\Util\JsonLD;
15 use Friendica\Util\LDSignature;
16 use Friendica\Protocol\ActivityPub;
19 * @brief ActivityPub Receiver Protocol class
22 * - Update (Image, Video, Article, Note)
26 * Check what this is meant to do:
32 * - Undo Accept (Problem: This could invert a contact accept or an event accept)
35 * - Possibly using the LD-JSON parser
39 const PUBLIC_COLLECTION = 'as:Public';
40 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
41 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image'];
42 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
45 * Checks if the web request is done for the AP protocol
49 public static function isRequest()
51 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
52 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
56 * Checks incoming message from the inbox
60 * @param integer $uid User ID
62 public static function processInbox($body, $header, $uid)
64 $http_signer = HTTPSignature::getSigner($body, $header);
65 if (empty($http_signer)) {
66 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
69 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
72 $activity = json_decode($body, true);
74 if (empty($activity)) {
75 logger('Invalid body.', LOGGER_DEBUG);
79 $ldactivity = JsonLD::compact($activity);
81 $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
83 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
85 if (LDSignature::isSigned($activity)) {
86 $ld_signer = LDSignature::getSigner($activity);
87 if (empty($ld_signer)) {
88 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
90 if (!empty($ld_signer && ($actor == $http_signer))) {
91 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
93 } elseif (!empty($ld_signer)) {
94 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
96 } elseif ($actor == $http_signer) {
97 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
100 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
101 $trust_source = false;
103 } elseif ($actor == $http_signer) {
104 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
105 $trust_source = true;
107 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
108 $trust_source = false;
111 self::processActivity($ldactivity, $body, $uid, $trust_source);
115 * Prepare the object array
117 * @param array $activity
118 * @param integer $uid User ID
119 * @param $trust_source
121 * @return array with object data
123 private static function prepareObjectData($activity, $uid, &$trust_source)
125 $actor = JsonLD::fetchElement($activity, 'as:actor');
127 logger('Empty actor', LOGGER_DEBUG);
131 $type = JsonLD::fetchElement($activity, '@type');
133 // Fetch all receivers from to, cc, bto and bcc
134 $receivers = self::getReceivers($activity, $actor);
136 // When it is a delivery to a personal inbox we add that user to the receivers
138 $owner = User::getOwnerDataById($uid);
139 $additional = ['uid:' . $uid => $uid];
140 $receivers = array_merge($receivers, $additional);
143 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
145 $object_id = JsonLD::fetchElement($activity, 'as:object');
146 if (empty($object_id)) {
147 logger('No object found', LOGGER_DEBUG);
151 // Fetch the content only on activities where this matters
152 if (in_array($type, ['as:Create', 'as:Announce'])) {
153 if ($type == 'as:Announce') {
154 $trust_source = false;
156 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source);
157 if (empty($object_data)) {
158 logger("Object data couldn't be processed", LOGGER_DEBUG);
161 // We had been able to retrieve the object data - so we can trust the source
162 $trust_source = true;
163 } elseif (in_array($type, ['as:Like', 'as:Dislike'])) {
164 // Create a mostly empty array out of the activity data (instead of the object).
165 // This way we later don't have to check for the existence of ech individual array element.
166 $object_data = self::processObject($activity);
167 $object_data['name'] = $type;
168 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor');
169 $object_data['object_id'] = $object_id;
170 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
173 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
174 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object');
175 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor');
176 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
177 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
180 $object_data = self::addActivityFields($object_data, $activity);
182 $object_data['type'] = $type;
183 $object_data['actor'] = $actor;
184 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
186 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
192 * Processes the activity object
194 * @param array $activity Array with activity data
195 * @param string $body
196 * @param integer $uid User ID
197 * @param boolean $trust_source Do we trust the source?
199 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
201 $type = JsonLD::fetchElement($activity, '@type');
203 logger('Empty type', LOGGER_DEBUG);
207 if (!JsonLD::fetchElement($activity, 'as:object')) {
208 logger('Empty object', LOGGER_DEBUG);
212 if (!JsonLD::fetchElement($activity, 'as:actor')) {
213 logger('Empty actor', LOGGER_DEBUG);
218 // $trust_source is called by reference and is set to true if the content was retrieved successfully
219 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
220 if (empty($object_data)) {
221 logger('No object data found', LOGGER_DEBUG);
225 if (!$trust_source) {
226 logger('No trust for activity type "' . $type . '", so we quit now.', LOGGER_DEBUG);
233 ActivityPub\Processor::createItem($object_data, $body);
237 ActivityPub\Processor::likeItem($object_data, $body);
241 ActivityPub\Processor::dislikeItem($object_data, $body);
245 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
247 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
248 ActivityPub\Processor::updatePerson($object_data, $body);
253 if ($object_data['object_type'] == 'as:Tombstone') {
254 ActivityPub\Processor::deleteItem($object_data, $body);
255 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
256 ActivityPub\Processor::deletePerson($object_data, $body);
261 ActivityPub\Processor::followUser($object_data);
265 if ($object_data['object_type'] == 'as:Follow') {
266 ActivityPub\Processor::acceptFollowUser($object_data);
271 if ($object_data['object_type'] == 'as:Follow') {
272 ActivityPub\Processor::rejectFollowUser($object_data);
277 if ($object_data['object_type'] == 'as:Follow') {
278 ActivityPub\Processor::undoFollowUser($object_data);
279 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
280 ActivityPub\Processor::undoActivity($object_data);
285 logger('Unknown activity: ' . $type, LOGGER_DEBUG);
291 * Fetch the receiver list from an activity array
293 * @param array $activity
294 * @param string $actor
296 * @return array with receivers (user id)
298 private static function getReceivers($activity, $actor)
302 // When it is an answer, we inherite the receivers from the parent
303 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo');
304 if (!empty($replyto)) {
305 $parents = Item::select(['uid'], ['uri' => $replyto]);
306 while ($parent = Item::fetch($parents)) {
307 $receivers['uid:' . $parent['uid']] = $parent['uid'];
311 if (!empty($actor)) {
312 $profile = APContact::getByURL($actor);
313 $followers = defaults($profile, 'followers', '');
315 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
317 logger('Empty actor', LOGGER_DEBUG);
321 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
322 $receiver_list = JsonLD::fetchElementArray($activity, $element);
323 if (empty($receiver_list)) {
327 foreach ($receiver_list as $receiver) {
328 if ($receiver == self::PUBLIC_COLLECTION) {
329 $receivers['uid:0'] = 0;
332 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
333 // This will most likely catch all OStatus connections to Mastodon
334 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
335 , 'archive' => false, 'pending' => false];
336 $contacts = DBA::select('contact', ['uid'], $condition);
337 while ($contact = DBA::fetch($contacts)) {
338 if ($contact['uid'] != 0) {
339 $receivers['uid:' . $contact['uid']] = $contact['uid'];
342 DBA::close($contacts);
345 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
346 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
347 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
348 $contacts = DBA::select('contact', ['uid'], $condition);
349 while ($contact = DBA::fetch($contacts)) {
350 if ($contact['uid'] != 0) {
351 $receivers['uid:' . $contact['uid']] = $contact['uid'];
354 DBA::close($contacts);
358 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
359 $contact = DBA::selectFirst('contact', ['uid'], $condition);
360 if (!DBA::isResult($contact)) {
363 $receivers['uid:' . $contact['uid']] = $contact['uid'];
367 self::switchContacts($receivers, $actor);
373 * Switches existing contacts to ActivityPub
375 * @param integer $cid Contact ID
376 * @param integer $uid User ID
377 * @param string $url Profile URL
379 private static function switchContact($cid, $uid, $url)
381 $profile = ActivityPub::probeProfile($url);
382 if (empty($profile)) {
386 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
388 $photo = $profile['photo'];
389 unset($profile['photo']);
390 unset($profile['baseurl']);
392 $profile['nurl'] = normalise_link($profile['url']);
393 DBA::update('contact', $profile, ['id' => $cid]);
395 Contact::updateAvatar($photo, $uid, $cid);
397 // Send a new follow request to be sure that the connection still exists
398 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
399 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
400 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
410 private static function switchContacts($receivers, $actor)
416 foreach ($receivers as $receiver) {
417 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
418 if (DBA::isResult($contact)) {
419 self::switchContact($contact['id'], $receiver, $actor);
422 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
423 if (DBA::isResult($contact)) {
424 self::switchContact($contact['id'], $receiver, $actor);
432 * @param $object_data
433 * @param array $activity
437 private static function addActivityFields($object_data, $activity)
439 if (!empty($activity['published']) && empty($object_data['published'])) {
440 $object_data['published'] = JsonLD::fetchElement($activity, 'published', '@value');
443 if (!empty($activity['updated']) && empty($object_data['updated'])) {
444 $object_data['updated'] = JsonLD::fetchElement($activity, 'updated', '@value');
447 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
448 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid');
451 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
452 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo');
455 if (!empty($activity['instrument'])) {
456 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
462 * Fetches the object data from external ressources if needed
464 * @param string $object_id Object ID of the the provided object
465 * @param array $object The provided object array
466 * @param boolean $trust_source Do we trust the provided object?
468 * @return array with trusted and valid object data
470 private static function fetchObject($object_id, $object = [], $trust_source = false)
472 // By fetching the type we check if the object is complete.
473 $type = JsonLD::fetchElement($object, '@type');
475 if (!$trust_source || empty($type)) {
476 $data = ActivityPub::fetchContent($object_id);
478 $object = JsonLD::compact($data);
479 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
481 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
483 $item = Item::selectFirst([], ['uri' => $object_id]);
484 if (!DBA::isResult($item)) {
485 logger('Object with url ' . $object_id . ' was not found locally.', LOGGER_DEBUG);
488 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
489 $data = ActivityPub\Transmitter::createNote($item);
490 $object = JsonLD::compact($data);
493 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
496 $type = JsonLD::fetchElement($object, '@type');
499 logger('Empty type', LOGGER_DEBUG);
503 if (in_array($type, self::CONTENT_TYPES)) {
504 return self::processObject($object);
507 if ($type == 'as:Announce') {
508 $object_id = JsonLD::fetchElement($object, 'object');
509 if (empty($object_id)) {
512 return self::fetchObject($object_id);
515 logger('Unhandled object type: ' . $type, LOGGER_DEBUG);
519 * Convert tags from JSON-LD format into a simplified format
521 * @param array $tags Tags in JSON-LD format
523 * @return array with tags in a simplified format
525 private static function processTags($tags)
533 foreach ($tags as $tag) {
538 $taglist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
539 'href' => JsonLD::fetchElement($tag, 'as:href'),
540 'name' => JsonLD::fetchElement($tag, 'as:name')];
546 * Convert attachments from JSON-LD format into a simplified format
548 * @param array $attachments Attachments in JSON-LD format
550 * @return array with attachmants in a simplified format
552 private static function processAttachments($attachments)
556 if (empty($attachments)) {
560 foreach ($attachments as $attachment) {
561 if (empty($attachment)) {
565 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
566 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType'),
567 'name' => JsonLD::fetchElement($attachment, 'as:name'),
568 'url' => JsonLD::fetchElement($attachment, 'as:url')];
574 * Fetches data from the object part of an activity
576 * @param array $object
580 private static function processObject($object)
582 if (!JsonLD::fetchElement($object, '@id')) {
587 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
588 $object_data['id'] = JsonLD::fetchElement($object, '@id');
590 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo');
592 if (empty($object_data['reply-to-id'])) {
593 $object_data['reply-to-id'] = $object_data['id'];
596 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
597 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
599 if (empty($object_data['updated'])) {
600 $object_data['updated'] = $object_data['published'];
603 if (empty($object_data['published']) && !empty($object_data['updated'])) {
604 $object_data['published'] = $object_data['updated'];
607 $actor = JsonLD::fetchElement($object, 'as:attributedTo');
609 $actor = JsonLD::fetchElement($object, 'as:actor');
612 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid');
613 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment');
614 $object_data['actor'] = $object_data['author'] = $actor;
615 $object_data['context'] = JsonLD::fetchElement($object, 'as:context');
616 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation');
617 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
618 $object_data['name'] = JsonLD::fetchElement($object, 'as:name');
619 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary');
620 $object_data['content'] = JsonLD::fetchElement($object, 'as:content');
621 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
622 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
623 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
624 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
625 // $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service'); // todo
626 $object_data['service'] = null;
627 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url');
629 // Special treatment for Hubzilla links
630 if (is_array($object_data['alternate-url'])) {
631 if (!empty($object['as:url'])) {
632 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href');
634 $object_data['alternate-url'] = null;
638 $object_data['receiver'] = self::getReceivers($object, $object_data['actor']);
640 // Common object data:
643 // @context, type, actor, signature, mediaType, duration, replies, icon
645 // Also missing: (Defined in the standard, but currently unused)
646 // audience, preview, endTime, startTime, generator, image
651 // contentMap, announcement_count, announcements, context_id, likes, like_count
652 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
657 // category, licence, language, commentsEnabled
660 // views, waitTranscoding, state, support, subtitleLanguage
661 // likes, dislikes, shares, comments