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;
17 use Friendica\Model\Conversation;
18 use Friendica\Util\DateTimeFormat;
21 * @brief ActivityPub Receiver Protocol class
24 * - Update (Image, Video, Article, Note)
28 * Check what this is meant to do:
34 * - Undo Accept (Problem: This could invert a contact accept or an event accept)
38 const PUBLIC_COLLECTION = 'as:Public';
39 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
40 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image'];
41 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
44 * Checks if the web request is done for the AP protocol
48 public static function isRequest()
50 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
51 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
55 * Checks incoming message from the inbox
59 * @param integer $uid User ID
61 public static function processInbox($body, $header, $uid)
63 $http_signer = HTTPSignature::getSigner($body, $header);
64 if (empty($http_signer)) {
65 logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
68 logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
71 $activity = json_decode($body, true);
73 if (empty($activity)) {
74 logger('Invalid body.', LOGGER_DEBUG);
78 $ldactivity = JsonLD::compact($activity);
80 $actor = JsonLD::fetchElement($ldactivity, 'as:actor');
82 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
84 if (LDSignature::isSigned($activity)) {
85 $ld_signer = LDSignature::getSigner($activity);
86 if (empty($ld_signer)) {
87 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
89 if (!empty($ld_signer && ($actor == $http_signer))) {
90 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
92 } elseif (!empty($ld_signer)) {
93 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
95 } elseif ($actor == $http_signer) {
96 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
99 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
100 $trust_source = false;
102 } elseif ($actor == $http_signer) {
103 logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
104 $trust_source = true;
106 logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
107 $trust_source = false;
110 self::processActivity($ldactivity, $body, $uid, $trust_source);
114 * Fetches the object type for a given object id
116 * @param array $activity
117 * @param string $object_id Object ID of the the provided object
119 * @return string with object type
121 private static function fetchObjectType($activity, $object_id)
124 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
125 if (!empty($object_type)) {
129 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
130 // We just assume "note" since it doesn't make a difference for the further processing
134 $profile = APContact::getByURL($object_id);
135 if (!empty($profile['type'])) {
136 return 'as:' . $profile['type'];
139 $data = ActivityPub::fetchContent($object_id);
141 $object = JsonLD::compact($data);
142 $type = JsonLD::fetchElement($object, '@type');
152 * Prepare the object array
154 * @param array $activity
155 * @param integer $uid User ID
156 * @param $trust_source
158 * @return array with object data
160 private static function prepareObjectData($activity, $uid, &$trust_source)
162 $actor = JsonLD::fetchElement($activity, 'as:actor');
164 logger('Empty actor', LOGGER_DEBUG);
168 $type = JsonLD::fetchElement($activity, '@type');
170 // Fetch all receivers from to, cc, bto and bcc
171 $receivers = self::getReceivers($activity, $actor);
173 // When it is a delivery to a personal inbox we add that user to the receivers
175 $owner = User::getOwnerDataById($uid);
176 $additional = ['uid:' . $uid => $uid];
177 $receivers = array_merge($receivers, $additional);
180 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
182 $object_id = JsonLD::fetchElement($activity, 'as:object');
183 if (empty($object_id)) {
184 logger('No object found', LOGGER_DEBUG);
188 $object_type = self::fetchObjectType($activity, $object_id);
190 // Fetch the content only on activities where this matters
191 if (in_array($type, ['as:Create', 'as:Announce'])) {
192 if ($type == 'as:Announce') {
193 $trust_source = false;
195 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source);
196 if (empty($object_data)) {
197 logger("Object data couldn't be processed", LOGGER_DEBUG);
200 // We had been able to retrieve the object data - so we can trust the source
201 $trust_source = true;
202 } elseif (in_array($type, ['as:Like', 'as:Dislike'])) {
203 // Create a mostly empty array out of the activity data (instead of the object).
204 // This way we later don't have to check for the existence of ech individual array element.
205 $object_data = self::processObject($activity);
206 $object_data['name'] = $type;
207 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor');
208 $object_data['object_id'] = $object_id;
209 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
212 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
213 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object');
214 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor');
215 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
216 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
219 $object_data = self::addActivityFields($object_data, $activity);
221 if (empty($object_data['object_type'])) {
222 $object_data['object_type'] = $object_type;
225 $object_data['type'] = $type;
226 $object_data['actor'] = $actor;
227 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
229 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
235 * Store the unprocessed data into the conversation table
236 * This has to be done outside the regular function,
237 * since we store everything - not only item posts.
239 * @param array $activity Array with activity data
240 * @param string $body The raw message
242 private static function storeConversation($activity, $body)
244 if (empty($body) || empty($activity['id'])) {
249 'protocol' => Conversation::PARCEL_ACTIVITYPUB,
250 'item-uri' => $activity['id'],
251 'reply-to-uri' => defaults($activity, 'reply-to-id', ''),
252 'conversation-href' => defaults($activity, 'context', ''),
253 'conversation-uri' => defaults($activity, 'conversation', ''),
255 'received' => DateTimeFormat::utcNow()];
257 DBA::insert('conversation', $conversation, true);
261 * Processes the activity object
263 * @param array $activity Array with activity data
264 * @param string $body
265 * @param integer $uid User ID
266 * @param boolean $trust_source Do we trust the source?
268 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
270 $type = JsonLD::fetchElement($activity, '@type');
272 logger('Empty type', LOGGER_DEBUG);
276 if (!JsonLD::fetchElement($activity, 'as:object')) {
277 logger('Empty object', LOGGER_DEBUG);
281 if (!JsonLD::fetchElement($activity, 'as:actor')) {
282 logger('Empty actor', LOGGER_DEBUG);
287 // $trust_source is called by reference and is set to true if the content was retrieved successfully
288 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
289 if (empty($object_data)) {
290 logger('No object data found', LOGGER_DEBUG);
294 if (!$trust_source) {
295 logger('No trust for activity type "' . $type . '", so we quit now.', LOGGER_DEBUG);
299 self::storeConversation($object_data, $body);
301 // Internal flag for thread completion. See Processor.php
302 if (!empty($activity['thread-completion'])) {
303 $object_data['thread-completion'] = $activity['thread-completion'];
309 ActivityPub\Processor::createItem($object_data);
313 ActivityPub\Processor::likeItem($object_data);
317 ActivityPub\Processor::dislikeItem($object_data);
321 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
323 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
324 ActivityPub\Processor::updatePerson($object_data, $body);
329 if ($object_data['object_type'] == 'as:Tombstone') {
330 ActivityPub\Processor::deleteItem($object_data, $body);
331 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
332 ActivityPub\Processor::deletePerson($object_data, $body);
337 ActivityPub\Processor::followUser($object_data);
341 if ($object_data['object_type'] == 'as:Follow') {
342 ActivityPub\Processor::acceptFollowUser($object_data);
347 if ($object_data['object_type'] == 'as:Follow') {
348 ActivityPub\Processor::rejectFollowUser($object_data);
353 if ($object_data['object_type'] == 'as:Follow') {
354 ActivityPub\Processor::undoFollowUser($object_data);
355 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
356 ActivityPub\Processor::undoActivity($object_data);
361 logger('Unknown activity: ' . $type, LOGGER_DEBUG);
367 * Fetch the receiver list from an activity array
369 * @param array $activity
370 * @param string $actor
372 * @return array with receivers (user id)
374 private static function getReceivers($activity, $actor)
378 // When it is an answer, we inherite the receivers from the parent
379 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo');
380 if (!empty($replyto)) {
381 $parents = Item::select(['uid'], ['uri' => $replyto]);
382 while ($parent = Item::fetch($parents)) {
383 $receivers['uid:' . $parent['uid']] = $parent['uid'];
387 if (!empty($actor)) {
388 $profile = APContact::getByURL($actor);
389 $followers = defaults($profile, 'followers', '');
391 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
393 logger('Empty actor', LOGGER_DEBUG);
397 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
398 $receiver_list = JsonLD::fetchElementArray($activity, $element);
399 if (empty($receiver_list)) {
403 foreach ($receiver_list as $receiver) {
404 if ($receiver == self::PUBLIC_COLLECTION) {
405 $receivers['uid:0'] = 0;
408 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
409 // This will most likely catch all OStatus connections to Mastodon
410 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
411 , 'archive' => false, 'pending' => false];
412 $contacts = DBA::select('contact', ['uid'], $condition);
413 while ($contact = DBA::fetch($contacts)) {
414 if ($contact['uid'] != 0) {
415 $receivers['uid:' . $contact['uid']] = $contact['uid'];
418 DBA::close($contacts);
421 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
422 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
423 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
424 $contacts = DBA::select('contact', ['uid'], $condition);
425 while ($contact = DBA::fetch($contacts)) {
426 if ($contact['uid'] != 0) {
427 $receivers['uid:' . $contact['uid']] = $contact['uid'];
430 DBA::close($contacts);
434 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
435 $contact = DBA::selectFirst('contact', ['uid'], $condition);
436 if (!DBA::isResult($contact)) {
439 $receivers['uid:' . $contact['uid']] = $contact['uid'];
443 self::switchContacts($receivers, $actor);
449 * Switches existing contacts to ActivityPub
451 * @param integer $cid Contact ID
452 * @param integer $uid User ID
453 * @param string $url Profile URL
455 private static function switchContact($cid, $uid, $url)
457 $profile = ActivityPub::probeProfile($url);
458 if (empty($profile)) {
462 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' to ActivityPub');
464 $photo = $profile['photo'];
465 unset($profile['photo']);
466 unset($profile['baseurl']);
468 $profile['nurl'] = normalise_link($profile['url']);
469 DBA::update('contact', $profile, ['id' => $cid]);
471 Contact::updateAvatar($photo, $uid, $cid);
473 // Send a new follow request to be sure that the connection still exists
474 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND]])) {
475 ActivityPub\Transmitter::sendActivity('Follow', $profile['url'], $uid);
476 logger('Send a new follow request to ' . $profile['url'] . ' for user ' . $uid, LOGGER_DEBUG);
486 private static function switchContacts($receivers, $actor)
492 foreach ($receivers as $receiver) {
493 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
494 if (DBA::isResult($contact)) {
495 self::switchContact($contact['id'], $receiver, $actor);
498 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
499 if (DBA::isResult($contact)) {
500 self::switchContact($contact['id'], $receiver, $actor);
508 * @param $object_data
509 * @param array $activity
513 private static function addActivityFields($object_data, $activity)
515 if (!empty($activity['published']) && empty($object_data['published'])) {
516 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
519 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
520 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid');
523 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
529 * Fetches the object data from external ressources if needed
531 * @param string $object_id Object ID of the the provided object
532 * @param array $object The provided object array
533 * @param boolean $trust_source Do we trust the provided object?
535 * @return array with trusted and valid object data
537 private static function fetchObject($object_id, $object = [], $trust_source = false)
539 // By fetching the type we check if the object is complete.
540 $type = JsonLD::fetchElement($object, '@type');
542 if (!$trust_source || empty($type)) {
543 $data = ActivityPub::fetchContent($object_id);
545 $object = JsonLD::compact($data);
546 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
548 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
550 $item = Item::selectFirst([], ['uri' => $object_id]);
551 if (!DBA::isResult($item)) {
552 logger('Object with url ' . $object_id . ' was not found locally.', LOGGER_DEBUG);
555 logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
556 $data = ActivityPub\Transmitter::createNote($item);
557 $object = JsonLD::compact($data);
560 logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
563 $type = JsonLD::fetchElement($object, '@type');
566 logger('Empty type', LOGGER_DEBUG);
570 if (in_array($type, self::CONTENT_TYPES)) {
571 return self::processObject($object);
574 if ($type == 'as:Announce') {
575 $object_id = JsonLD::fetchElement($object, 'object');
576 if (empty($object_id)) {
579 return self::fetchObject($object_id);
582 logger('Unhandled object type: ' . $type, LOGGER_DEBUG);
586 * Convert tags from JSON-LD format into a simplified format
588 * @param array $tags Tags in JSON-LD format
590 * @return array with tags in a simplified format
592 private static function processTags($tags)
600 foreach ($tags as $tag) {
605 $taglist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
606 'href' => JsonLD::fetchElement($tag, 'as:href'),
607 'name' => JsonLD::fetchElement($tag, 'as:name')];
613 * Convert attachments from JSON-LD format into a simplified format
615 * @param array $attachments Attachments in JSON-LD format
617 * @return array with attachmants in a simplified format
619 private static function processAttachments($attachments)
623 if (empty($attachments)) {
627 foreach ($attachments as $attachment) {
628 if (empty($attachment)) {
632 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
633 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType'),
634 'name' => JsonLD::fetchElement($attachment, 'as:name'),
635 'url' => JsonLD::fetchElement($attachment, 'as:url')];
641 * Fetches data from the object part of an activity
643 * @param array $object
647 private static function processObject($object)
649 if (!JsonLD::fetchElement($object, '@id')) {
654 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
655 $object_data['id'] = JsonLD::fetchElement($object, '@id');
657 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo');
659 if (empty($object_data['reply-to-id'])) {
660 $object_data['reply-to-id'] = $object_data['id'];
663 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
664 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
666 if (empty($object_data['updated'])) {
667 $object_data['updated'] = $object_data['published'];
670 if (empty($object_data['published']) && !empty($object_data['updated'])) {
671 $object_data['published'] = $object_data['updated'];
674 $actor = JsonLD::fetchElement($object, 'as:attributedTo');
676 $actor = JsonLD::fetchElement($object, 'as:actor');
679 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid');
680 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment');
681 $object_data['actor'] = $object_data['author'] = $actor;
682 $object_data['context'] = JsonLD::fetchElement($object, 'as:context');
683 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation');
684 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
685 $object_data['name'] = JsonLD::fetchElement($object, 'as:name');
686 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary');
687 $object_data['content'] = JsonLD::fetchElement($object, 'as:content');
688 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
689 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
690 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
691 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
692 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
693 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
694 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
695 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
696 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
697 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url');
699 // Special treatment for Hubzilla links
700 if (is_array($object_data['alternate-url'])) {
701 if (!empty($object['as:url'])) {
702 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href');
704 $object_data['alternate-url'] = null;
708 $object_data['receiver'] = self::getReceivers($object, $object_data['actor']);
710 // Common object data:
713 // @context, type, actor, signature, mediaType, duration, replies, icon
715 // Also missing: (Defined in the standard, but currently unused)
716 // audience, preview, endTime, startTime, image
721 // contentMap, announcement_count, announcements, context_id, likes, like_count
722 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
727 // category, licence, language, commentsEnabled
730 // views, waitTranscoding, state, support, subtitleLanguage
731 // likes, dislikes, shares, comments