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);
117 * @param array $activity
118 * @param integer $uid User ID
119 * @param $trust_source
123 private static function prepareObjectData($ldactivity, $uid, &$trust_source)
125 $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
127 logger('Empty actor', LOGGER_DEBUG);
131 $type = JsonLD::fetchElement($ldactivity, '@type');
133 // Fetch all receivers from to, cc, bto and bcc
134 $receivers = self::getReceivers($ldactivity, $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($ldactivity, '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, $ldactivity['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($ldactivity);
167 $object_data['name'] = $type;
168 $object_data['author'] = JsonLD::fetchElement($ldactivity, 'as:actor');
169 $object_data['object'] = $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($ldactivity, '@id');
174 $object_data['object'] = $ldactivity['as:object'];
175 $object_data['object_type'] = JsonLD::fetchElement($ldactivity, 'as:object', '@type');
178 $object_data = self::addActivityFields($object_data, $ldactivity);
180 $object_data['type'] = $type;
181 $object_data['actor'] = $actor;
182 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
184 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
190 * Processes the activity object
192 * @param array $activity Array with activity data
193 * @param string $body
194 * @param integer $uid User ID
195 * @param boolean $trust_source Do we trust the source?
197 public static function processActivity($ldactivity, $body = '', $uid = null, $trust_source = false)
199 $type = JsonLD::fetchElement($ldactivity, '@type');
201 logger('Empty type', LOGGER_DEBUG);
205 if (!JsonLD::fetchElement($ldactivity, 'as:object')) {
206 logger('Empty object', LOGGER_DEBUG);
210 if (!JsonLD::fetchElement($ldactivity, 'as:actor')) {
211 logger('Empty actor', LOGGER_DEBUG);
216 // $trust_source is called by reference and is set to true if the content was retrieved successfully
217 $object_data = self::prepareObjectData($ldactivity, $uid, $trust_source);
218 if (empty($object_data)) {
219 logger('No object data found', LOGGER_DEBUG);
223 if (!$trust_source) {
224 logger('No trust for activity type "' . $type . '", so we quit now.', LOGGER_DEBUG);
231 ActivityPub\Processor::createItem($object_data, $body);
235 ActivityPub\Processor::likeItem($object_data, $body);
239 ActivityPub\Processor::dislikeItem($object_data, $body);
243 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
245 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
246 ActivityPub\Processor::updatePerson($object_data, $body);
251 if ($object_data['object_type'] == 'as:Tombstone') {
252 ActivityPub\Processor::deleteItem($object_data, $body);
253 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
254 ActivityPub\Processor::deletePerson($object_data, $body);
259 ActivityPub\Processor::followUser($object_data);
263 if ($object_data['object_type'] == 'as:Follow') {
264 ActivityPub\Processor::acceptFollowUser($object_data);
269 if ($object_data['object_type'] == 'as:Follow') {
270 ActivityPub\Processor::rejectFollowUser($object_data);
275 if ($object_data['object_type'] == 'as:Follow') {
276 ActivityPub\Processor::undoFollowUser($object_data);
277 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
278 ActivityPub\Processor::undoActivity($object_data);
283 logger('Unknown activity: ' . $type, LOGGER_DEBUG);
289 * Fetch the receiver list from an activity array
291 * @param array $activity
292 * @param string $actor
294 * @return array with receivers (user id)
296 private static function getReceivers($activity, $actor)
300 // When it is an answer, we inherite the receivers from the parent
301 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo');
302 if (!empty($replyto)) {
303 $parents = Item::select(['uid'], ['uri' => $replyto]);
304 while ($parent = Item::fetch($parents)) {
305 $receivers['uid:' . $parent['uid']] = $parent['uid'];
309 if (!empty($actor)) {
310 $profile = APContact::getByURL($actor);
311 $followers = defaults($profile, 'followers', '');
313 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
315 logger('Empty actor', LOGGER_DEBUG);
319 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
320 $receiver_list = JsonLD::fetchElementArray($activity, $element);
321 if (empty($receiver_list)) {
325 foreach ($receiver_list as $receiver) {
326 if ($receiver == self::PUBLIC_COLLECTION) {
327 $receivers['uid:0'] = 0;
330 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
331 // This will most likely catch all OStatus connections to Mastodon
332 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
333 , 'archive' => false, 'pending' => false];
334 $contacts = DBA::select('contact', ['uid'], $condition);
335 while ($contact = DBA::fetch($contacts)) {
336 if ($contact['uid'] != 0) {
337 $receivers['uid:' . $contact['uid']] = $contact['uid'];
340 DBA::close($contacts);
343 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
344 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
345 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
346 $contacts = DBA::select('contact', ['uid'], $condition);
347 while ($contact = DBA::fetch($contacts)) {
348 if ($contact['uid'] != 0) {
349 $receivers['uid:' . $contact['uid']] = $contact['uid'];
352 DBA::close($contacts);
356 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
357 $contact = DBA::selectFirst('contact', ['uid'], $condition);
358 if (!DBA::isResult($contact)) {
361 $receivers['uid:' . $contact['uid']] = $contact['uid'];
365 self::switchContacts($receivers, $actor);
371 * Switches existing contacts to ActivityPub
373 * @param integer $cid Contact ID
374 * @param integer $uid User ID
375 * @param string $url Profile URL
377 private static function switchContact($cid, $uid, $url)
379 $profile = ActivityPub::probeProfile($url);
380 if (empty($profile)) {
384 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
386 $photo = $profile['photo'];
387 unset($profile['photo']);
388 unset($profile['baseurl']);
390 $profile['nurl'] = normalise_link($profile['url']);
391 DBA::update('contact', $profile, ['id' => $cid]);
393 Contact::updateAvatar($photo, $uid, $cid);
395 // Send a new follow request to be sure that the connection still exists
396 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
397 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
398 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
408 private static function switchContacts($receivers, $actor)
414 foreach ($receivers as $receiver) {
415 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
416 if (DBA::isResult($contact)) {
417 self::switchContact($contact['id'], $receiver, $actor);
420 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
421 if (DBA::isResult($contact)) {
422 self::switchContact($contact['id'], $receiver, $actor);
430 * @param $object_data
431 * @param array $activity
435 private static function addActivityFields($object_data, $activity)
437 if (!empty($activity['published']) && empty($object_data['published'])) {
438 $object_data['published'] = JsonLD::fetchElement($activity, 'published', '@value');
441 if (!empty($activity['updated']) && empty($object_data['updated'])) {
442 $object_data['updated'] = JsonLD::fetchElement($activity, 'updated', '@value');
445 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
446 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid');
449 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
450 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo');
453 if (!empty($activity['instrument'])) {
454 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
460 * Fetches the object data from external ressources if needed
462 * @param string $object_id Object ID of the the provided object
463 * @param array $object The provided object array
464 * @param boolean $trust_source Do we trust the provided object?
466 * @return array with trusted and valid object data
468 private static function fetchObject($object_id, $object = [], $trust_source = false)
470 // By fetching the type we check if the object is complete.
471 $type = JsonLD::fetchElement($object, '@type');
473 if (!$trust_source || empty($type)) {
474 $data = ActivityPub::fetchContent($object_id);
476 $object = JsonLD::compact($data);
477 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
479 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
481 $item = Item::selectFirst([], ['uri' => $object_id]);
482 if (!DBA::isResult($item)) {
483 logger('Object with url ' . $object_id . ' was not found locally.', LOGGER_DEBUG);
486 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
487 $data = ActivityPub\Transmitter::createNote($item);
488 $object = JsonLD::compact($data);
491 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
494 $type = JsonLD::fetchElement($object, '@type');
497 logger('Empty type', LOGGER_DEBUG);
501 if (in_array($type, self::CONTENT_TYPES)) {
502 return self::processObject($object);
505 if ($type == 'as:Announce') {
506 $object_id = JsonLD::fetchElement($object, 'object');
507 if (empty($object_id)) {
510 return self::fetchObject($object_id);
513 logger('Unhandled object type: ' . $type, LOGGER_DEBUG);
517 * Convert tags from JSON-LD format into a simplified format
519 * @param array $tags Tags in JSON-LD format
521 * @return array with tags in a simplified format
523 private static function processTags($tags)
531 foreach ($tags as $tag) {
536 $taglist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
537 'href' => JsonLD::fetchElement($tag, 'as:href'),
538 'name' => JsonLD::fetchElement($tag, 'as:name')];
544 * Convert attachments from JSON-LD format into a simplified format
546 * @param array $attachments Attachments in JSON-LD format
548 * @return array with attachmants in a simplified format
550 private static function processAttachments($attachments)
554 if (empty($attachments)) {
558 foreach ($attachments as $attachment) {
559 if (empty($attachment)) {
563 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
564 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType'),
565 'name' => JsonLD::fetchElement($attachment, 'as:name'),
566 'url' => JsonLD::fetchElement($attachment, 'as:url')];
572 * Fetches data from the object part of an activity
574 * @param array $object
578 private static function processObject($object)
580 if (!JsonLD::fetchElement($object, '@id')) {
585 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
586 $object_data['id'] = JsonLD::fetchElement($object, '@id');
588 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo');
590 if (empty($object_data['reply-to-id'])) {
591 $object_data['reply-to-id'] = $object_data['id'];
594 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
595 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
597 if (empty($object_data['updated'])) {
598 $object_data['updated'] = $object_data['published'];
601 if (empty($object_data['published']) && !empty($object_data['updated'])) {
602 $object_data['published'] = $object_data['updated'];
605 $actor = JsonLD::fetchElement($object, 'as:attributedTo');
607 $actor = JsonLD::fetchElement($object, 'as:actor');
610 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid');
611 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment');
612 $object_data['actor'] = $object_data['author'] = $actor;
613 $object_data['context'] = JsonLD::fetchElement($object, 'as:context');
614 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation');
615 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
616 $object_data['name'] = JsonLD::fetchElement($object, 'as:name');
617 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary');
618 $object_data['content'] = JsonLD::fetchElement($object, 'as:content');
619 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
620 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
621 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
622 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
623 // $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service'); // todo
624 $object_data['service'] = null;
625 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url');
627 // Special treatment for Hubzilla links
628 if (is_array($object_data['alternate-url'])) {
629 if (!empty($object['as:url'])) {
630 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href');
632 $object_data['alternate-url'] = null;
636 $object_data['receiver'] = self::getReceivers($object, $object_data['actor']);
638 // Common object data:
641 // @context, type, actor, signature, mediaType, duration, replies, icon
643 // Also missing: (Defined in the standard, but currently unused)
644 // audience, preview, endTime, startTime, generator, image
649 // contentMap, announcement_count, announcements, context_id, likes, like_count
650 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
655 // category, licence, language, commentsEnabled
658 // views, waitTranscoding, state, support, subtitleLanguage
659 // likes, dislikes, shares, comments