3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Model\Contact;
31 use Friendica\Model\APContact;
32 use Friendica\Model\Item;
33 use Friendica\Model\User;
34 use Friendica\Protocol\Activity;
35 use Friendica\Protocol\ActivityPub;
36 use Friendica\Util\HTTPSignature;
37 use Friendica\Util\JsonLD;
38 use Friendica\Util\LDSignature;
39 use Friendica\Util\Strings;
42 * ActivityPub Receiver Protocol class
47 * Check what this is meant to do:
56 const PUBLIC_COLLECTION = 'as:Public';
57 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
58 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio'];
59 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
61 const TARGET_UNKNOWN = 0;
66 const TARGET_FOLLOWER = 5;
67 const TARGET_ANSWER = 6;
68 const TARGET_GLOBAL = 7;
71 * Checks if the web request is done for the AP protocol
73 * @return bool is it AP?
75 public static function isRequest()
77 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
78 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
82 * Checks incoming message from the inbox
86 * @param integer $uid User ID
89 public static function processInbox($body, $header, $uid)
91 $activity = json_decode($body, true);
92 if (empty($activity)) {
93 Logger::warning('Invalid body.');
97 $ldactivity = JsonLD::compact($activity);
99 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
101 $apcontact = APContact::getByURL($actor);
102 if (!empty($apcontact) && ($apcontact['type'] == 'Application') && ($apcontact['nick'] == 'relay')) {
103 self::processRelayPost($ldactivity, $actor);
107 $http_signer = HTTPSignature::getSigner($body, $header);
108 if (empty($http_signer)) {
109 Logger::warning('Invalid HTTP signature, message will be discarded.');
112 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
115 $signer = [$http_signer];
117 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
119 if (LDSignature::isSigned($activity)) {
120 $ld_signer = LDSignature::getSigner($activity);
121 if (empty($ld_signer)) {
122 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
123 } elseif ($ld_signer != $http_signer) {
124 $signer[] = $ld_signer;
126 if (!empty($ld_signer && ($actor == $http_signer))) {
127 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
128 $trust_source = true;
129 } elseif (!empty($ld_signer)) {
130 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
131 $trust_source = true;
132 } elseif ($actor == $http_signer) {
133 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
134 $trust_source = true;
136 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
137 $trust_source = false;
139 } elseif ($actor == $http_signer) {
140 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
141 $trust_source = true;
143 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
144 $trust_source = false;
147 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
151 * Process incoming posts from relays
153 * @param array $activity
154 * @param string $actor
157 private static function processRelayPost(array $activity, string $actor)
159 $type = JsonLD::fetchElement($activity, '@type');
161 Logger::info('Empty type', ['activity' => $activity]);
165 if ($type != 'as:Announce') {
166 Logger::info('Not an announcement', ['activity' => $activity]);
170 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
171 if (empty($object_id)) {
172 Logger::info('No object id found', ['activity' => $activity]);
176 Logger::info('Got relayed message id', ['id' => $object_id]);
178 $item_id = Item::searchByLink($object_id);
180 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
184 $id = Processor::fetchMissingActivity($object_id, [], $actor);
186 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
190 $item_id = Item::searchByLink($object_id);
192 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
194 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
199 * Fetches the object type for a given object id
201 * @param array $activity
202 * @param string $object_id Object ID of the the provided object
203 * @param integer $uid User ID
205 * @return string with object type
206 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
207 * @throws \ImagickException
209 private static function fetchObjectType($activity, $object_id, $uid = 0)
211 if (!empty($activity['as:object'])) {
212 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
213 if (!empty($object_type)) {
218 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
219 // We just assume "note" since it doesn't make a difference for the further processing
223 $profile = APContact::getByURL($object_id);
224 if (!empty($profile['type'])) {
225 return 'as:' . $profile['type'];
228 $data = ActivityPub::fetchContent($object_id, $uid);
230 $object = JsonLD::compact($data);
231 $type = JsonLD::fetchElement($object, '@type');
241 * Prepare the object array
243 * @param array $activity Array with activity data
244 * @param integer $uid User ID
245 * @param boolean $push Message had been pushed to our system
246 * @param boolean $trust_source Do we trust the source?
248 * @return array with object data
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
254 $id = JsonLD::fetchElement($activity, '@id');
255 if (!empty($id) && !$trust_source) {
256 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
257 if (!empty($fetched_activity)) {
258 $object = JsonLD::compact($fetched_activity);
259 $fetched_id = JsonLD::fetchElement($object, '@id');
260 if ($fetched_id == $id) {
261 Logger::info('Activity had been fetched successfully', ['id' => $id]);
262 $trust_source = true;
265 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
268 Logger::info('Activity could not been fetched', ['id' => $id]);
272 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
274 Logger::info('Empty actor', ['activity' => $activity]);
278 $type = JsonLD::fetchElement($activity, '@type');
280 // Fetch all receivers from to, cc, bto and bcc
281 $receiverdata = self::getReceivers($activity, $actor);
282 $receivers = $reception_types = [];
283 foreach ($receiverdata as $key => $data) {
284 $receivers[$key] = $data['uid'];
285 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
288 // When it is a delivery to a personal inbox we add that user to the receivers
290 $additional = [$uid => $uid];
291 $receivers = array_replace($receivers, $additional);
292 if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
293 $reception_types[$uid] = self::TARGET_BCC;
296 // We possibly need some user to fetch private content,
297 // so we fetch the first out ot the list.
298 $uid = self::getFirstUserFromReceivers($receivers);
301 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
302 if (empty($object_id)) {
303 Logger::log('No object found', Logger::DEBUG);
307 if (!is_string($object_id)) {
308 Logger::info('Invalid object id', ['object' => $object_id]);
312 $object_type = self::fetchObjectType($activity, $object_id, $uid);
314 // Fetch the content only on activities where this matters
315 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
316 // Always fetch on "Announce"
317 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
318 if (empty($object_data)) {
319 Logger::log("Object data couldn't be processed", Logger::DEBUG);
323 $object_data['object_id'] = $object_id;
325 if ($type == 'as:Announce') {
326 $object_data['push'] = false;
328 $object_data['push'] = $push;
331 // Test if it is an answer to a mail
332 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
333 $object_data['directmessage'] = true;
335 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
337 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
338 // Create a mostly empty array out of the activity data (instead of the object).
339 // This way we later don't have to check for the existence of ech individual array element.
340 $object_data = self::processObject($activity);
341 $object_data['name'] = $type;
342 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
343 $object_data['object_id'] = $object_id;
344 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
345 } elseif (in_array($type, ['as:Add'])) {
347 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
348 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
349 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
350 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
351 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
354 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
355 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
356 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
357 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
358 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
360 // An Undo is done on the object of an object, so we need that type as well
361 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
362 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
366 $object_data = self::addActivityFields($object_data, $activity);
368 if (empty($object_data['object_type'])) {
369 $object_data['object_type'] = $object_type;
372 $object_data['type'] = $type;
373 $object_data['actor'] = $actor;
374 $object_data['item_receiver'] = $receivers;
375 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
376 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
378 $author = $object_data['author'] ?? $actor;
379 if (!empty($author) && !empty($object_data['id'])) {
380 $author_host = parse_url($author, PHP_URL_HOST);
381 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
382 if ($author_host == $id_host) {
383 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
385 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
386 $trust_source = false;
390 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
396 * Fetches the first user id from the receiver array
398 * @param array $receivers Array with receivers
399 * @return integer user id;
401 public static function getFirstUserFromReceivers($receivers)
403 foreach ($receivers as $receiver) {
404 if (!empty($receiver)) {
412 * Processes the activity object
414 * @param array $activity Array with activity data
415 * @param string $body
416 * @param integer $uid User ID
417 * @param boolean $trust_source Do we trust the source?
418 * @param boolean $push Message had been pushed to our system
421 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
423 $type = JsonLD::fetchElement($activity, '@type');
425 Logger::info('Empty type', ['activity' => $activity]);
429 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
430 Logger::info('Empty object', ['activity' => $activity]);
434 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
436 Logger::info('Empty actor', ['activity' => $activity]);
440 if (is_array($activity['as:object'])) {
441 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
446 // Test the provided signatures against the actor and "attributedTo"
448 if (!empty($attributed_to) && !empty($actor)) {
449 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
451 $trust_source = in_array($actor, $signer);
455 // $trust_source is called by reference and is set to true if the content was retrieved successfully
456 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
457 if (empty($object_data)) {
458 Logger::info('No object data found', ['activity' => $activity]);
462 if (!$trust_source) {
463 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
467 if (!empty($body) && empty($object_data['raw'])) {
468 $object_data['raw'] = $body;
471 // Internal flag for thread completion. See Processor.php
472 if (!empty($activity['thread-completion'])) {
473 $object_data['thread-completion'] = $activity['thread-completion'];
476 // Internal flag for posts that arrived via relay
477 if (!empty($activity['from-relay'])) {
478 $object_data['from-relay'] = $activity['from-relay'];
483 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
484 $item = ActivityPub\Processor::createItem($object_data);
485 ActivityPub\Processor::postItem($object_data, $item);
490 if ($object_data['object_type'] == 'as:tag') {
491 ActivityPub\Processor::addTag($object_data);
496 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
497 $object_data['thread-completion'] = true;
499 $item = ActivityPub\Processor::createItem($object_data);
504 $item['post-type'] = Item::PT_ANNOUNCEMENT;
505 ActivityPub\Processor::postItem($object_data, $item);
507 $announce_object_data = self::processObject($activity);
508 $announce_object_data['name'] = $type;
509 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
510 $announce_object_data['object_id'] = $object_data['object_id'];
511 $announce_object_data['object_type'] = $object_data['object_type'];
512 $announce_object_data['push'] = $push;
515 $announce_object_data['raw'] = $body;
518 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
523 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
524 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
529 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
530 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
534 case 'as:TentativeAccept':
535 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
536 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
541 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
542 ActivityPub\Processor::updateItem($object_data);
543 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
544 ActivityPub\Processor::updatePerson($object_data);
549 if ($object_data['object_type'] == 'as:Tombstone') {
550 ActivityPub\Processor::deleteItem($object_data);
551 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
552 ActivityPub\Processor::deletePerson($object_data);
557 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
558 ActivityPub\Processor::followUser($object_data);
559 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
560 $object_data['reply-to-id'] = $object_data['object_id'];
561 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
566 if ($object_data['object_type'] == 'as:Follow') {
567 ActivityPub\Processor::acceptFollowUser($object_data);
568 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
569 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
574 if ($object_data['object_type'] == 'as:Follow') {
575 ActivityPub\Processor::rejectFollowUser($object_data);
576 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
577 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
582 if (($object_data['object_type'] == 'as:Follow') &&
583 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
584 ActivityPub\Processor::undoFollowUser($object_data);
585 } elseif (($object_data['object_type'] == 'as:Accept') &&
586 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
587 ActivityPub\Processor::rejectFollowUser($object_data);
588 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
589 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
590 ActivityPub\Processor::undoActivity($object_data);
595 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
601 * Fetch the receiver list from an activity array
603 * @param array $activity
604 * @param string $actor
606 * @param boolean $fetch_unlisted
608 * @return array with receivers (user id)
611 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
613 $reply = $receivers = [];
615 // When it is an answer, we inherite the receivers from the parent
616 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
617 if (!empty($replyto)) {
620 // Fix possibly wrong item URI (could be an answer to a plink uri)
621 $fixedReplyTo = Item::getURIByLink($replyto);
622 if (!empty($fixedReplyTo)) {
623 $reply[] = $fixedReplyTo;
627 // Fetch all posts that refer to the object id
628 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
629 if (!empty($object_id)) {
630 $reply[] = $object_id;
633 if (!empty($reply)) {
634 $parents = Item::select(['uid'], ['uri' => $reply]);
635 while ($parent = Item::fetch($parents)) {
636 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
640 if (!empty($actor)) {
641 $profile = APContact::getByURL($actor);
642 $followers = $profile['followers'] ?? '';
644 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
646 Logger::info('Empty actor', ['activity' => $activity]);
650 // We have to prevent false follower assumptions upon thread completions
651 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
653 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
654 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
655 if (empty($receiver_list)) {
659 foreach ($receiver_list as $receiver) {
660 if ($receiver == self::PUBLIC_COLLECTION) {
661 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
664 // Add receiver "-1" for unlisted posts
665 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
666 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
669 // Fetch the receivers for the public and the followers collection
670 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
671 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
675 // Fetching all directly addressed receivers
676 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
677 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
678 if (!DBA::isResult($contact)) {
682 // Check if the potential receiver is following the actor
683 // Exception: The receiver is targetted via "to" or this is a comment
684 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
685 $networks = Protocol::FEDERATED;
686 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
687 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
689 // Forum posts are only accepted from forum contacts
690 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
691 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
694 if (!DBA::exists('contact', $condition)) {
699 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
700 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
703 $type = self::TARGET_TO;
706 $type = self::TARGET_CC;
709 $type = self::TARGET_BTO;
712 $type = self::TARGET_BCC;
716 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
721 self::switchContacts($receivers, $actor);
727 * Fetch the receiver list of a given actor
729 * @param string $actor
731 * @param array $receivers
732 * @param integer $target_type
734 * @return array with receivers (user id)
737 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
739 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
740 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
742 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
743 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
744 while ($contact = DBA::fetch($contacts)) {
745 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
746 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
749 DBA::close($contacts);
751 // The queries are split because of performance issues
752 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
753 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
754 while ($contact = DBA::fetch($contacts)) {
755 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
756 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
759 DBA::close($contacts);
764 * Tests if the contact is a valid receiver for this actor
766 * @param array $contact
767 * @param string $actor
770 * @return bool with receivers (user id)
773 private static function isValidReceiverForActor($contact, $tags)
775 // Are we following the contact? Then this is a valid receiver
776 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
780 // When the possible receiver isn't a community, then it is no valid receiver
781 $owner = User::getOwnerDataById($contact['uid']);
782 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
786 // Is the community account tagged?
787 foreach ($tags as $tag) {
788 if ($tag['type'] != 'Mention') {
792 if (Strings::compareLink($tag['href'], $owner['url'])) {
801 * Switches existing contacts to ActivityPub
803 * @param integer $cid Contact ID
804 * @param integer $uid User ID
805 * @param string $url Profile URL
806 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
807 * @throws \ImagickException
809 public static function switchContact($cid, $uid, $url)
811 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
812 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
816 if (Contact::updateFromProbe($cid)) {
817 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
820 // Send a new follow request to be sure that the connection still exists
821 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
822 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
823 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
832 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
833 * @throws \ImagickException
835 private static function switchContacts($receivers, $actor)
841 foreach ($receivers as $receiver) {
842 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
843 if (DBA::isResult($contact)) {
844 self::switchContact($contact['id'], $receiver['uid'], $actor);
847 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
848 if (DBA::isResult($contact)) {
849 self::switchContact($contact['id'], $receiver['uid'], $actor);
857 * @param $object_data
858 * @param array $activity
862 private static function addActivityFields($object_data, $activity)
864 if (!empty($activity['published']) && empty($object_data['published'])) {
865 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
868 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
869 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
872 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
873 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
875 if (!empty($object_data['object_id'])) {
876 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
877 $objectId = Item::getURIByLink($object_data['object_id']);
878 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
879 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
880 $object_data['object_id'] = $objectId;
888 * Fetches the object data from external ressources if needed
890 * @param string $object_id Object ID of the the provided object
891 * @param array $object The provided object array
892 * @param boolean $trust_source Do we trust the provided object?
893 * @param integer $uid User ID for the signature that we use to fetch data
895 * @return array|false with trusted and valid object data
896 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
897 * @throws \ImagickException
899 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
901 // By fetching the type we check if the object is complete.
902 $type = JsonLD::fetchElement($object, '@type');
904 if (!$trust_source || empty($type)) {
905 $data = ActivityPub::fetchContent($object_id, $uid);
907 $object = JsonLD::compact($data);
908 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
910 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
912 $item = Item::selectFirst([], ['uri' => $object_id]);
913 if (!DBA::isResult($item)) {
914 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
917 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
918 $data = ActivityPub\Transmitter::createNote($item);
919 $object = JsonLD::compact($data);
922 $id = JsonLD::fetchElement($object, '@id');
924 Logger::info('Empty id');
928 if ($id != $object_id) {
929 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
933 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
936 $type = JsonLD::fetchElement($object, '@type');
938 Logger::info('Empty type');
942 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
943 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
944 $object_data = self::processObject($object);
947 $object_data['raw'] = json_encode($data);
952 if ($type == 'as:Announce') {
953 $object_id = JsonLD::fetchElement($object, 'object', '@id');
954 if (empty($object_id) || !is_string($object_id)) {
957 return self::fetchObject($object_id, [], false, $uid);
960 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
965 * Convert tags from JSON-LD format into a simplified format
967 * @param array $tags Tags in JSON-LD format
969 * @return array with tags in a simplified format
971 public static function processTags(array $tags)
975 foreach ($tags as $tag) {
980 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
981 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
982 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
984 if (empty($element['type'])) {
988 if (empty($element['href'])) {
989 $element['href'] = $element['name'];
992 $taglist[] = $element;
998 * Convert emojis from JSON-LD format into a simplified format
1000 * @param array $emojis
1001 * @return array with emojis in a simplified format
1003 private static function processEmojis(array $emojis)
1007 foreach ($emojis as $emoji) {
1008 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1012 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1013 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1016 $emojilist[] = $element;
1023 * Convert attachments from JSON-LD format into a simplified format
1025 * @param array $attachments Attachments in JSON-LD format
1027 * @return array Attachments in a simplified format
1029 private static function processAttachments(array $attachments)
1033 // Removes empty values
1034 $attachments = array_filter($attachments);
1036 foreach ($attachments as $attachment) {
1037 switch (JsonLD::fetchElement($attachment, '@type')) {
1042 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1043 foreach ($urls as $url) {
1044 // Single scalar URL case
1045 if (is_string($url)) {
1050 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1051 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1052 if (Strings::startsWith($mediaType, 'image')) {
1061 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1062 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1064 'image' => $pageImage,
1069 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1070 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1071 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1072 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1076 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1077 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1078 $imagePreviewUrl = null;
1080 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1081 $imageVariants = [];
1082 $previewVariants = [];
1083 foreach ($urls as $url) {
1084 // Scalar URL, no discrimination possible
1085 if (is_string($url)) {
1086 $imageFullUrl = $url;
1090 // Not sure what to do with a different Link media type than the base Image, we skip
1091 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1095 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1097 // Default URL choice if no discriminating width is provided
1098 $imageFullUrl = $href ?? $imageFullUrl;
1100 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1102 if ($href && $width) {
1103 $imageVariants[$width] = $href;
1104 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1105 $previewVariants[abs(632 - $width)] = $href;
1109 if ($imageVariants) {
1110 // Taking the maximum size image
1111 ksort($imageVariants);
1112 $imageFullUrl = array_pop($imageVariants);
1114 // Taking the minimum number distance to the target distance
1115 ksort($previewVariants);
1116 $imagePreviewUrl = array_shift($previewVariants);
1119 unset($imageVariants);
1120 unset($previewVariants);
1124 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1125 'mediaType' => $mediaType,
1126 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1127 'url' => $imageFullUrl,
1128 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1133 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1134 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1135 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1136 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1145 * Fetch the original source or content with the "language" Markdown or HTML
1147 * @param array $object
1148 * @param array $object_data
1151 * @throws \Exception
1153 private static function getSource($object, $object_data)
1155 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1156 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1157 if (!empty($object_data['source'])) {
1158 return $object_data;
1161 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1162 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1163 if (!empty($object_data['source'])) {
1164 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1165 return $object_data;
1168 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1169 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1170 if (!empty($object_data['source'])) {
1171 $object_data['source'] = HTML::toBBCode($object_data['source']);
1172 return $object_data;
1175 return $object_data;
1179 * Check if the "as:url" element is an array with multiple links
1180 * This is the case with audio and video posts.
1181 * Then the links are added as attachments
1183 * @param array $object The raw object
1184 * @param array $object_data The parsed object data for later processing
1185 * @return array the object data
1187 private static function processAttachmentUrls(array $object, array $object_data) {
1188 // Check if this is some url with multiple links
1189 if (empty($object['as:url'])) {
1190 return $object_data;
1193 $urls = $object['as:url'];
1194 $keys = array_keys($urls);
1195 if (!is_numeric(array_pop($keys))) {
1196 return $object_data;
1201 foreach ($urls as $url) {
1202 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1206 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1211 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1212 if (empty($mediatype)) {
1216 if ($mediatype == 'text/html') {
1217 $object_data['alternate-url'] = $href;
1220 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1222 if ($filetype == 'audio') {
1223 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1224 } elseif ($filetype == 'video') {
1225 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1227 // We save bandwidth by using a moderate height
1228 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1229 if (!empty($attachments[$filetype]['height']) &&
1230 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1234 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1238 foreach ($attachments as $type => $attachment) {
1239 $object_data['attachments'][] = ['type' => $type,
1240 'mediaType' => $attachment['type'],
1242 'url' => $attachment['url']];
1244 return $object_data;
1248 * Fetches data from the object part of an activity
1250 * @param array $object
1253 * @throws \Exception
1255 private static function processObject($object)
1257 if (!JsonLD::fetchElement($object, '@id')) {
1262 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1263 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1264 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1266 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1267 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1268 $object_data['reply-to-id'] = $object_data['id'];
1270 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1271 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1272 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1273 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1274 $object_data['reply-to-id'] = $replyToId;
1278 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1279 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1281 if (empty($object_data['updated'])) {
1282 $object_data['updated'] = $object_data['published'];
1285 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1286 $object_data['published'] = $object_data['updated'];
1289 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1290 if (empty($actor)) {
1291 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1294 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1295 $location = JsonLD::fetchElement($location, 'location', '@value');
1297 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1298 // down to HTML and then finally format to plaintext.
1299 $location = Markdown::convert($location);
1300 $location = BBCode::convert($location);
1301 $location = HTML::toPlaintext($location);
1304 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1305 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1306 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1307 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1308 $object_data['actor'] = $object_data['author'] = $actor;
1309 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1310 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1311 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1312 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1313 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1314 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1315 $object_data = self::getSource($object, $object_data);
1316 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1317 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1318 $object_data['location'] = $location;
1319 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1320 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1321 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1322 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1323 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1324 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1325 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1326 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1327 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1328 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1330 // Special treatment for Hubzilla links
1331 if (is_array($object_data['alternate-url'])) {
1332 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1334 if (!is_string($object_data['alternate-url'])) {
1335 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1339 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1340 $object_data = self::processAttachmentUrls($object, $object_data);
1343 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1344 $receivers = $reception_types = [];
1345 foreach ($receiverdata as $key => $data) {
1346 $receivers[$key] = $data['uid'];
1347 $reception_types[$data['uid']] = $data['type'] ?? 0;
1350 $object_data['receiver'] = $receivers;
1351 $object_data['reception_type'] = $reception_types;
1353 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1354 unset($object_data['receiver'][-1]);
1355 unset($object_data['reception_type'][-1]);
1357 // Common object data:
1360 // @context, type, actor, signature, mediaType, duration, replies, icon
1362 // Also missing: (Defined in the standard, but currently unused)
1363 // audience, preview, endTime, startTime, image
1368 // contentMap, announcement_count, announcements, context_id, likes, like_count
1369 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1374 // category, licence, language, commentsEnabled
1377 // views, waitTranscoding, state, support, subtitleLanguage
1378 // likes, dislikes, shares, comments
1380 return $object_data;