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);
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
156 private static function processRelayPost(array $activity)
158 $type = JsonLD::fetchElement($activity, '@type');
160 Logger::info('Empty type', ['activity' => $activity]);
164 if ($type != 'as:Announce') {
165 Logger::info('Not an announcement', ['activity' => $activity]);
168 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
169 if (empty($object_id)) {
170 Logger::info('No object id found', ['activity' => $activity]);
173 Logger::info('Got relayed message id', ['id' => $object_id]);
175 $item_id = Item::searchByLink($object_id);
177 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
181 Processor::fetchMissingActivity($object_id);
185 * Fetches the object type for a given object id
187 * @param array $activity
188 * @param string $object_id Object ID of the the provided object
189 * @param integer $uid User ID
191 * @return string with object type
192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193 * @throws \ImagickException
195 private static function fetchObjectType($activity, $object_id, $uid = 0)
197 if (!empty($activity['as:object'])) {
198 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
199 if (!empty($object_type)) {
204 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
205 // We just assume "note" since it doesn't make a difference for the further processing
209 $profile = APContact::getByURL($object_id);
210 if (!empty($profile['type'])) {
211 return 'as:' . $profile['type'];
214 $data = ActivityPub::fetchContent($object_id, $uid);
216 $object = JsonLD::compact($data);
217 $type = JsonLD::fetchElement($object, '@type');
227 * Prepare the object array
229 * @param array $activity Array with activity data
230 * @param integer $uid User ID
231 * @param boolean $push Message had been pushed to our system
232 * @param boolean $trust_source Do we trust the source?
234 * @return array with object data
235 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
236 * @throws \ImagickException
238 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
240 $id = JsonLD::fetchElement($activity, '@id');
241 if (!empty($id) && !$trust_source) {
242 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
243 if (!empty($fetched_activity)) {
244 $object = JsonLD::compact($fetched_activity);
245 $fetched_id = JsonLD::fetchElement($object, '@id');
246 if ($fetched_id == $id) {
247 Logger::info('Activity had been fetched successfully', ['id' => $id]);
248 $trust_source = true;
251 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
254 Logger::info('Activity could not been fetched', ['id' => $id]);
258 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
260 Logger::info('Empty actor', ['activity' => $activity]);
264 $type = JsonLD::fetchElement($activity, '@type');
266 // Fetch all receivers from to, cc, bto and bcc
267 $receiverdata = self::getReceivers($activity, $actor);
268 $receivers = $reception_types = [];
269 foreach ($receiverdata as $key => $data) {
270 $receivers[$key] = $data['uid'];
271 $reception_types[$data['uid']] = $data['type'] ?? 0;
274 // When it is a delivery to a personal inbox we add that user to the receivers
276 $additional = ['uid:' . $uid => $uid];
277 $receivers = array_merge($receivers, $additional);
278 if (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
279 $reception_types[$uid] = self::TARGET_BCC;
282 // We possibly need some user to fetch private content,
283 // so we fetch the first out ot the list.
284 $uid = self::getFirstUserFromReceivers($receivers);
287 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
288 if (empty($object_id)) {
289 Logger::log('No object found', Logger::DEBUG);
293 if (!is_string($object_id)) {
294 Logger::info('Invalid object id', ['object' => $object_id]);
298 $object_type = self::fetchObjectType($activity, $object_id, $uid);
300 // Fetch the content only on activities where this matters
301 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
302 // Always fetch on "Announce"
303 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
304 if (empty($object_data)) {
305 Logger::log("Object data couldn't be processed", Logger::DEBUG);
309 $object_data['object_id'] = $object_id;
311 if ($type == 'as:Announce') {
312 $object_data['push'] = false;
314 $object_data['push'] = $push;
317 // Test if it is an answer to a mail
318 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
319 $object_data['directmessage'] = true;
321 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
323 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
324 // Create a mostly empty array out of the activity data (instead of the object).
325 // This way we later don't have to check for the existence of ech individual array element.
326 $object_data = self::processObject($activity);
327 $object_data['name'] = $type;
328 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
329 $object_data['object_id'] = $object_id;
330 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
331 } elseif (in_array($type, ['as:Add'])) {
333 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
334 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
335 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
336 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
337 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
340 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
341 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
342 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
343 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
344 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
346 // An Undo is done on the object of an object, so we need that type as well
347 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
348 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
352 $object_data = self::addActivityFields($object_data, $activity);
354 if (empty($object_data['object_type'])) {
355 $object_data['object_type'] = $object_type;
358 $object_data['type'] = $type;
359 $object_data['actor'] = $actor;
360 $object_data['item_receiver'] = $receivers;
361 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
362 $object_data['reception_type'] = array_merge($object_data['reception_type'] ?? [], $reception_types);
364 $author = $object_data['author'] ?? $actor;
365 if (!empty($author) && !empty($object_data['id'])) {
366 $author_host = parse_url($author, PHP_URL_HOST);
367 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
368 if ($author_host == $id_host) {
369 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
371 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
372 $trust_source = false;
376 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
382 * Fetches the first user id from the receiver array
384 * @param array $receivers Array with receivers
385 * @return integer user id;
387 public static function getFirstUserFromReceivers($receivers)
389 foreach ($receivers as $receiver) {
390 if (!empty($receiver)) {
398 * Processes the activity object
400 * @param array $activity Array with activity data
401 * @param string $body
402 * @param integer $uid User ID
403 * @param boolean $trust_source Do we trust the source?
404 * @param boolean $push Message had been pushed to our system
407 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
409 $type = JsonLD::fetchElement($activity, '@type');
411 Logger::info('Empty type', ['activity' => $activity]);
415 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
416 Logger::info('Empty object', ['activity' => $activity]);
420 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
422 Logger::info('Empty actor', ['activity' => $activity]);
426 if (is_array($activity['as:object'])) {
427 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
432 // Test the provided signatures against the actor and "attributedTo"
434 if (!empty($attributed_to) && !empty($actor)) {
435 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
437 $trust_source = in_array($actor, $signer);
441 // $trust_source is called by reference and is set to true if the content was retrieved successfully
442 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
443 if (empty($object_data)) {
444 Logger::info('No object data found', ['activity' => $activity]);
448 if (!$trust_source) {
449 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
453 if (!empty($body) && empty($object_data['raw'])) {
454 $object_data['raw'] = $body;
457 // Internal flag for thread completion. See Processor.php
458 if (!empty($activity['thread-completion'])) {
459 $object_data['thread-completion'] = $activity['thread-completion'];
464 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
465 $item = ActivityPub\Processor::createItem($object_data);
466 ActivityPub\Processor::postItem($object_data, $item);
471 if ($object_data['object_type'] == 'as:tag') {
472 ActivityPub\Processor::addTag($object_data);
477 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
478 $object_data['thread-completion'] = true;
480 $item = ActivityPub\Processor::createItem($object_data);
481 $item['post-type'] = Item::PT_ANNOUNCEMENT;
482 ActivityPub\Processor::postItem($object_data, $item);
484 $announce_object_data = self::processObject($activity);
485 $announce_object_data['name'] = $type;
486 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
487 $announce_object_data['object_id'] = $object_data['object_id'];
488 $announce_object_data['object_type'] = $object_data['object_type'];
489 $announce_object_data['push'] = $push;
492 $announce_object_data['raw'] = $body;
495 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
500 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
501 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
506 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
507 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
511 case 'as:TentativeAccept':
512 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
513 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
518 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
519 ActivityPub\Processor::updateItem($object_data);
520 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
521 ActivityPub\Processor::updatePerson($object_data);
526 if ($object_data['object_type'] == 'as:Tombstone') {
527 ActivityPub\Processor::deleteItem($object_data);
528 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
529 ActivityPub\Processor::deletePerson($object_data);
534 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
535 ActivityPub\Processor::followUser($object_data);
536 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
537 $object_data['reply-to-id'] = $object_data['object_id'];
538 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
543 if ($object_data['object_type'] == 'as:Follow') {
544 ActivityPub\Processor::acceptFollowUser($object_data);
545 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
546 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
551 if ($object_data['object_type'] == 'as:Follow') {
552 ActivityPub\Processor::rejectFollowUser($object_data);
553 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
554 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
559 if (($object_data['object_type'] == 'as:Follow') &&
560 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
561 ActivityPub\Processor::undoFollowUser($object_data);
562 } elseif (($object_data['object_type'] == 'as:Accept') &&
563 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
564 ActivityPub\Processor::rejectFollowUser($object_data);
565 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
566 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
567 ActivityPub\Processor::undoActivity($object_data);
572 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
578 * Fetch the receiver list from an activity array
580 * @param array $activity
581 * @param string $actor
583 * @param boolean $fetch_unlisted
585 * @return array with receivers (user id)
588 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
590 $reply = $receivers = [];
592 // When it is an answer, we inherite the receivers from the parent
593 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
594 if (!empty($replyto)) {
597 // Fix possibly wrong item URI (could be an answer to a plink uri)
598 $fixedReplyTo = Item::getURIByLink($replyto);
599 if (!empty($fixedReplyTo)) {
600 $reply[] = $fixedReplyTo;
604 // Fetch all posts that refer to the object id
605 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
606 if (!empty($object_id)) {
607 $reply[] = $object_id;
610 if (!empty($reply)) {
611 $parents = Item::select(['uid'], ['uri' => $reply]);
612 while ($parent = Item::fetch($parents)) {
613 $receivers['uid:' . $parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
617 if (!empty($actor)) {
618 $profile = APContact::getByURL($actor);
619 $followers = $profile['followers'] ?? '';
621 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
623 Logger::info('Empty actor', ['activity' => $activity]);
627 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
628 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
629 if (empty($receiver_list)) {
633 foreach ($receiver_list as $receiver) {
634 if ($receiver == self::PUBLIC_COLLECTION) {
635 $receivers['uid:0'] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
638 // Add receiver "-1" for unlisted posts
639 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
640 $receivers['uid:-1'] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
643 // Fetch the receivers for the public and the followers collection
644 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
645 $receivers = self::getReceiverForActor($actor, $tags, $receivers);
649 // Fetching all directly addressed receivers
650 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
651 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
652 if (!DBA::isResult($contact)) {
656 // Check if the potential receiver is following the actor
657 // Exception: The receiver is targetted via "to" or this is a comment
658 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
659 $networks = Protocol::FEDERATED;
660 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
661 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
663 // Forum posts are only accepted from forum contacts
664 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
665 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
668 if (!DBA::exists('contact', $condition)) {
673 $type = $receivers['uid:' . $contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
674 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
677 $type = self::TARGET_TO;
680 $type = self::TARGET_CC;
683 $type = self::TARGET_BTO;
686 $type = self::TARGET_BCC;
690 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
695 self::switchContacts($receivers, $actor);
701 * Fetch the receiver list of a given actor
703 * @param string $actor
706 * @return array with receivers (user id)
709 private static function getReceiverForActor($actor, $tags, $receivers)
711 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
712 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
714 $condition = DBA::mergeConditions($basecondition, ['nurl' => Strings::normaliseLink($actor)]);
715 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
716 while ($contact = DBA::fetch($contacts)) {
717 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
718 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
721 DBA::close($contacts);
723 // The queries are split because of performance issues
724 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?)", Strings::normaliseLink($actor), $actor]);
725 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
726 while ($contact = DBA::fetch($contacts)) {
727 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
728 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
731 DBA::close($contacts);
736 * Tests if the contact is a valid receiver for this actor
738 * @param array $contact
739 * @param string $actor
742 * @return bool with receivers (user id)
745 private static function isValidReceiverForActor($contact, $actor, $tags)
747 // Public contacts are no valid receiver
748 if ($contact['uid'] == 0) {
752 // Are we following the contact? Then this is a valid receiver
753 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
757 // When the possible receiver isn't a community, then it is no valid receiver
758 $owner = User::getOwnerDataById($contact['uid']);
759 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
763 // Is the community account tagged?
764 foreach ($tags as $tag) {
765 if ($tag['type'] != 'Mention') {
769 if ($tag['href'] == $owner['url']) {
778 * Switches existing contacts to ActivityPub
780 * @param integer $cid Contact ID
781 * @param integer $uid User ID
782 * @param string $url Profile URL
783 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
784 * @throws \ImagickException
786 public static function switchContact($cid, $uid, $url)
788 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
789 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
793 if (Contact::updateFromProbe($cid)) {
794 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
797 // Send a new follow request to be sure that the connection still exists
798 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
799 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
800 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
809 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
810 * @throws \ImagickException
812 private static function switchContacts($receivers, $actor)
818 foreach ($receivers as $receiver) {
819 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
820 if (DBA::isResult($contact)) {
821 self::switchContact($contact['id'], $receiver['uid'], $actor);
824 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
825 if (DBA::isResult($contact)) {
826 self::switchContact($contact['id'], $receiver['uid'], $actor);
834 * @param $object_data
835 * @param array $activity
839 private static function addActivityFields($object_data, $activity)
841 if (!empty($activity['published']) && empty($object_data['published'])) {
842 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
845 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
846 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
849 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
850 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
852 if (!empty($object_data['object_id'])) {
853 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
854 $objectId = Item::getURIByLink($object_data['object_id']);
855 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
856 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
857 $object_data['object_id'] = $objectId;
865 * Fetches the object data from external ressources if needed
867 * @param string $object_id Object ID of the the provided object
868 * @param array $object The provided object array
869 * @param boolean $trust_source Do we trust the provided object?
870 * @param integer $uid User ID for the signature that we use to fetch data
872 * @return array|false with trusted and valid object data
873 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
874 * @throws \ImagickException
876 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
878 // By fetching the type we check if the object is complete.
879 $type = JsonLD::fetchElement($object, '@type');
881 if (!$trust_source || empty($type)) {
882 $data = ActivityPub::fetchContent($object_id, $uid);
884 $object = JsonLD::compact($data);
885 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
887 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
889 $item = Item::selectFirst([], ['uri' => $object_id]);
890 if (!DBA::isResult($item)) {
891 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
894 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
895 $data = ActivityPub\Transmitter::createNote($item);
896 $object = JsonLD::compact($data);
899 $id = JsonLD::fetchElement($object, '@id');
901 Logger::info('Empty id');
905 if ($id != $object_id) {
906 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
910 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
913 $type = JsonLD::fetchElement($object, '@type');
915 Logger::info('Empty type');
919 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
920 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
921 $object_data = self::processObject($object);
924 $object_data['raw'] = json_encode($data);
929 if ($type == 'as:Announce') {
930 $object_id = JsonLD::fetchElement($object, 'object', '@id');
931 if (empty($object_id) || !is_string($object_id)) {
934 return self::fetchObject($object_id, [], false, $uid);
937 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
942 * Convert tags from JSON-LD format into a simplified format
944 * @param array $tags Tags in JSON-LD format
946 * @return array with tags in a simplified format
948 private static function processTags(array $tags)
952 foreach ($tags as $tag) {
957 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
958 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
959 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
961 if (empty($element['type'])) {
965 if (empty($element['href'])) {
966 $element['href'] = $element['name'];
969 $taglist[] = $element;
975 * Convert emojis from JSON-LD format into a simplified format
977 * @param array $emojis
978 * @return array with emojis in a simplified format
980 private static function processEmojis(array $emojis)
984 foreach ($emojis as $emoji) {
985 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
989 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
990 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
993 $emojilist[] = $element;
1000 * Convert attachments from JSON-LD format into a simplified format
1002 * @param array $attachments Attachments in JSON-LD format
1004 * @return array Attachments in a simplified format
1006 private static function processAttachments(array $attachments)
1010 // Removes empty values
1011 $attachments = array_filter($attachments);
1013 foreach ($attachments as $attachment) {
1014 switch (JsonLD::fetchElement($attachment, '@type')) {
1019 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1020 foreach ($urls as $url) {
1021 // Single scalar URL case
1022 if (is_string($url)) {
1027 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1028 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1029 if (Strings::startsWith($mediaType, 'image')) {
1038 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1039 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1041 'image' => $pageImage,
1046 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1047 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1048 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1049 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1053 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1054 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1055 $imagePreviewUrl = null;
1057 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1058 $imageVariants = [];
1059 $previewVariants = [];
1060 foreach ($urls as $url) {
1061 // Scalar URL, no discrimination possible
1062 if (is_string($url)) {
1063 $imageFullUrl = $url;
1067 // Not sure what to do with a different Link media type than the base Image, we skip
1068 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1072 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1074 // Default URL choice if no discriminating width is provided
1075 $imageFullUrl = $href ?? $imageFullUrl;
1077 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1079 if ($href && $width) {
1080 $imageVariants[$width] = $href;
1081 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1082 $previewVariants[abs(632 - $width)] = $href;
1086 if ($imageVariants) {
1087 // Taking the maximum size image
1088 ksort($imageVariants);
1089 $imageFullUrl = array_pop($imageVariants);
1091 // Taking the minimum number distance to the target distance
1092 ksort($previewVariants);
1093 $imagePreviewUrl = array_shift($previewVariants);
1096 unset($imageVariants);
1097 unset($previewVariants);
1101 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1102 'mediaType' => $mediaType,
1103 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1104 'url' => $imageFullUrl,
1105 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1110 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1111 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1112 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1113 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1122 * Fetch the original source or content with the "language" Markdown or HTML
1124 * @param array $object
1125 * @param array $object_data
1128 * @throws \Exception
1130 private static function getSource($object, $object_data)
1132 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1133 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1134 if (!empty($object_data['source'])) {
1135 return $object_data;
1138 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1139 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1140 if (!empty($object_data['source'])) {
1141 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1142 return $object_data;
1145 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1146 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1147 if (!empty($object_data['source'])) {
1148 $object_data['source'] = HTML::toBBCode($object_data['source']);
1149 return $object_data;
1152 return $object_data;
1156 * Check if the "as:url" element is an array with multiple links
1157 * This is the case with audio and video posts.
1158 * Then the links are added as attachments
1160 * @param array $object The raw object
1161 * @param array $object_data The parsed object data for later processing
1162 * @return array the object data
1164 private static function processAttachmentUrls(array $object, array $object_data) {
1165 // Check if this is some url with multiple links
1166 if (empty($object['as:url'])) {
1167 return $object_data;
1170 $urls = $object['as:url'];
1171 $keys = array_keys($urls);
1172 if (!is_numeric(array_pop($keys))) {
1173 return $object_data;
1178 foreach ($urls as $url) {
1179 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1183 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1188 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1189 if (empty($mediatype)) {
1193 if ($mediatype == 'text/html') {
1194 $object_data['alternate-url'] = $href;
1197 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1199 if ($filetype == 'audio') {
1200 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1201 } elseif ($filetype == 'video') {
1202 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1204 // We save bandwidth by using a moderate height
1205 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1206 if (!empty($attachments[$filetype]['height']) &&
1207 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1211 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1215 foreach ($attachments as $type => $attachment) {
1216 $object_data['attachments'][] = ['type' => $type,
1217 'mediaType' => $attachment['type'],
1219 'url' => $attachment['url']];
1221 return $object_data;
1225 * Fetches data from the object part of an activity
1227 * @param array $object
1230 * @throws \Exception
1232 private static function processObject($object)
1234 if (!JsonLD::fetchElement($object, '@id')) {
1239 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1240 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1241 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1243 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1244 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1245 $object_data['reply-to-id'] = $object_data['id'];
1247 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1248 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1249 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1250 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1251 $object_data['reply-to-id'] = $replyToId;
1255 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1256 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1258 if (empty($object_data['updated'])) {
1259 $object_data['updated'] = $object_data['published'];
1262 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1263 $object_data['published'] = $object_data['updated'];
1266 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1267 if (empty($actor)) {
1268 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1271 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1272 $location = JsonLD::fetchElement($location, 'location', '@value');
1274 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1275 // down to HTML and then finally format to plaintext.
1276 $location = Markdown::convert($location);
1277 $location = BBCode::convert($location);
1278 $location = HTML::toPlaintext($location);
1281 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1282 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1283 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1284 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1285 $object_data['actor'] = $object_data['author'] = $actor;
1286 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1287 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1288 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1289 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1290 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1291 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1292 $object_data = self::getSource($object, $object_data);
1293 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1294 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1295 $object_data['location'] = $location;
1296 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1297 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1298 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1299 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1300 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1301 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1302 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1303 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1304 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1305 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1307 // Special treatment for Hubzilla links
1308 if (is_array($object_data['alternate-url'])) {
1309 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1311 if (!is_string($object_data['alternate-url'])) {
1312 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1316 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1317 $object_data = self::processAttachmentUrls($object, $object_data);
1320 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1321 $receivers = $reception_types = [];
1322 foreach ($receiverdata as $key => $data) {
1323 $receivers[$key] = $data['uid'];
1324 $reception_types[$data['uid']] = $data['type'] ?? 0;
1327 $object_data['receiver'] = $receivers;
1328 $object_data['reception_type'] = $reception_types;
1330 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1331 unset($object_data['receiver']['uid:-1']);
1333 // Common object data:
1336 // @context, type, actor, signature, mediaType, duration, replies, icon
1338 // Also missing: (Defined in the standard, but currently unused)
1339 // audience, preview, endTime, startTime, image
1344 // contentMap, announcement_count, announcements, context_id, likes, like_count
1345 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1350 // category, licence, language, commentsEnabled
1353 // views, waitTranscoding, state, support, subtitleLanguage
1354 // likes, dislikes, shares, comments
1356 return $object_data;