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]);
169 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
170 if (empty($object_id)) {
171 Logger::info('No object id found', ['activity' => $activity]);
175 Logger::info('Got relayed message id', ['id' => $object_id]);
177 $item_id = Item::searchByLink($object_id);
179 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
183 Processor::fetchMissingActivity($object_id);
185 $item_id = Item::searchByLink($object_id);
187 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
189 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
194 * Fetches the object type for a given object id
196 * @param array $activity
197 * @param string $object_id Object ID of the the provided object
198 * @param integer $uid User ID
200 * @return string with object type
201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
202 * @throws \ImagickException
204 private static function fetchObjectType($activity, $object_id, $uid = 0)
206 if (!empty($activity['as:object'])) {
207 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
208 if (!empty($object_type)) {
213 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
214 // We just assume "note" since it doesn't make a difference for the further processing
218 $profile = APContact::getByURL($object_id);
219 if (!empty($profile['type'])) {
220 return 'as:' . $profile['type'];
223 $data = ActivityPub::fetchContent($object_id, $uid);
225 $object = JsonLD::compact($data);
226 $type = JsonLD::fetchElement($object, '@type');
236 * Prepare the object array
238 * @param array $activity Array with activity data
239 * @param integer $uid User ID
240 * @param boolean $push Message had been pushed to our system
241 * @param boolean $trust_source Do we trust the source?
243 * @return array with object data
244 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
245 * @throws \ImagickException
247 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
249 $id = JsonLD::fetchElement($activity, '@id');
250 if (!empty($id) && !$trust_source) {
251 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
252 if (!empty($fetched_activity)) {
253 $object = JsonLD::compact($fetched_activity);
254 $fetched_id = JsonLD::fetchElement($object, '@id');
255 if ($fetched_id == $id) {
256 Logger::info('Activity had been fetched successfully', ['id' => $id]);
257 $trust_source = true;
260 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
263 Logger::info('Activity could not been fetched', ['id' => $id]);
267 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
269 Logger::info('Empty actor', ['activity' => $activity]);
273 $type = JsonLD::fetchElement($activity, '@type');
275 // Fetch all receivers from to, cc, bto and bcc
276 $receiverdata = self::getReceivers($activity, $actor);
277 $receivers = $reception_types = [];
278 foreach ($receiverdata as $key => $data) {
279 $receivers[$key] = $data['uid'];
280 $reception_types[$data['uid']] = $data['type'] ?? 0;
283 // When it is a delivery to a personal inbox we add that user to the receivers
285 $additional = ['uid:' . $uid => $uid];
286 $receivers = array_merge($receivers, $additional);
287 if (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
288 $reception_types[$uid] = self::TARGET_BCC;
291 // We possibly need some user to fetch private content,
292 // so we fetch the first out ot the list.
293 $uid = self::getFirstUserFromReceivers($receivers);
296 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
297 if (empty($object_id)) {
298 Logger::log('No object found', Logger::DEBUG);
302 if (!is_string($object_id)) {
303 Logger::info('Invalid object id', ['object' => $object_id]);
307 $object_type = self::fetchObjectType($activity, $object_id, $uid);
309 // Fetch the content only on activities where this matters
310 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
311 // Always fetch on "Announce"
312 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
313 if (empty($object_data)) {
314 Logger::log("Object data couldn't be processed", Logger::DEBUG);
318 $object_data['object_id'] = $object_id;
320 if ($type == 'as:Announce') {
321 $object_data['push'] = false;
323 $object_data['push'] = $push;
326 // Test if it is an answer to a mail
327 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
328 $object_data['directmessage'] = true;
330 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
332 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
333 // Create a mostly empty array out of the activity data (instead of the object).
334 // This way we later don't have to check for the existence of ech individual array element.
335 $object_data = self::processObject($activity);
336 $object_data['name'] = $type;
337 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
338 $object_data['object_id'] = $object_id;
339 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
340 } elseif (in_array($type, ['as:Add'])) {
342 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
343 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
344 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
345 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
346 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
349 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
350 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
351 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
352 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
353 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
355 // An Undo is done on the object of an object, so we need that type as well
356 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
357 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
361 $object_data = self::addActivityFields($object_data, $activity);
363 if (empty($object_data['object_type'])) {
364 $object_data['object_type'] = $object_type;
367 $object_data['type'] = $type;
368 $object_data['actor'] = $actor;
369 $object_data['item_receiver'] = $receivers;
370 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
371 $object_data['reception_type'] = array_merge($object_data['reception_type'] ?? [], $reception_types);
373 $author = $object_data['author'] ?? $actor;
374 if (!empty($author) && !empty($object_data['id'])) {
375 $author_host = parse_url($author, PHP_URL_HOST);
376 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
377 if ($author_host == $id_host) {
378 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
380 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
381 $trust_source = false;
385 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
391 * Fetches the first user id from the receiver array
393 * @param array $receivers Array with receivers
394 * @return integer user id;
396 public static function getFirstUserFromReceivers($receivers)
398 foreach ($receivers as $receiver) {
399 if (!empty($receiver)) {
407 * Processes the activity object
409 * @param array $activity Array with activity data
410 * @param string $body
411 * @param integer $uid User ID
412 * @param boolean $trust_source Do we trust the source?
413 * @param boolean $push Message had been pushed to our system
416 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
418 $type = JsonLD::fetchElement($activity, '@type');
420 Logger::info('Empty type', ['activity' => $activity]);
424 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
425 Logger::info('Empty object', ['activity' => $activity]);
429 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
431 Logger::info('Empty actor', ['activity' => $activity]);
435 if (is_array($activity['as:object'])) {
436 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
441 // Test the provided signatures against the actor and "attributedTo"
443 if (!empty($attributed_to) && !empty($actor)) {
444 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
446 $trust_source = in_array($actor, $signer);
450 // $trust_source is called by reference and is set to true if the content was retrieved successfully
451 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
452 if (empty($object_data)) {
453 Logger::info('No object data found', ['activity' => $activity]);
457 if (!$trust_source) {
458 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
462 if (!empty($body) && empty($object_data['raw'])) {
463 $object_data['raw'] = $body;
466 // Internal flag for thread completion. See Processor.php
467 if (!empty($activity['thread-completion'])) {
468 $object_data['thread-completion'] = $activity['thread-completion'];
473 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
474 $item = ActivityPub\Processor::createItem($object_data);
475 ActivityPub\Processor::postItem($object_data, $item);
480 if ($object_data['object_type'] == 'as:tag') {
481 ActivityPub\Processor::addTag($object_data);
486 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
487 $object_data['thread-completion'] = true;
489 $item = ActivityPub\Processor::createItem($object_data);
490 $item['post-type'] = Item::PT_ANNOUNCEMENT;
491 ActivityPub\Processor::postItem($object_data, $item);
493 $announce_object_data = self::processObject($activity);
494 $announce_object_data['name'] = $type;
495 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
496 $announce_object_data['object_id'] = $object_data['object_id'];
497 $announce_object_data['object_type'] = $object_data['object_type'];
498 $announce_object_data['push'] = $push;
501 $announce_object_data['raw'] = $body;
504 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
509 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
510 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
515 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
516 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
520 case 'as:TentativeAccept':
521 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
522 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
527 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
528 ActivityPub\Processor::updateItem($object_data);
529 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
530 ActivityPub\Processor::updatePerson($object_data);
535 if ($object_data['object_type'] == 'as:Tombstone') {
536 ActivityPub\Processor::deleteItem($object_data);
537 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
538 ActivityPub\Processor::deletePerson($object_data);
543 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
544 ActivityPub\Processor::followUser($object_data);
545 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
546 $object_data['reply-to-id'] = $object_data['object_id'];
547 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
552 if ($object_data['object_type'] == 'as:Follow') {
553 ActivityPub\Processor::acceptFollowUser($object_data);
554 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
555 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
560 if ($object_data['object_type'] == 'as:Follow') {
561 ActivityPub\Processor::rejectFollowUser($object_data);
562 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
563 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
568 if (($object_data['object_type'] == 'as:Follow') &&
569 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
570 ActivityPub\Processor::undoFollowUser($object_data);
571 } elseif (($object_data['object_type'] == 'as:Accept') &&
572 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
573 ActivityPub\Processor::rejectFollowUser($object_data);
574 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
575 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
576 ActivityPub\Processor::undoActivity($object_data);
581 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
587 * Fetch the receiver list from an activity array
589 * @param array $activity
590 * @param string $actor
592 * @param boolean $fetch_unlisted
594 * @return array with receivers (user id)
597 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
599 $reply = $receivers = [];
601 // When it is an answer, we inherite the receivers from the parent
602 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
603 if (!empty($replyto)) {
606 // Fix possibly wrong item URI (could be an answer to a plink uri)
607 $fixedReplyTo = Item::getURIByLink($replyto);
608 if (!empty($fixedReplyTo)) {
609 $reply[] = $fixedReplyTo;
613 // Fetch all posts that refer to the object id
614 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
615 if (!empty($object_id)) {
616 $reply[] = $object_id;
619 if (!empty($reply)) {
620 $parents = Item::select(['uid'], ['uri' => $reply]);
621 while ($parent = Item::fetch($parents)) {
622 $receivers['uid:' . $parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
626 if (!empty($actor)) {
627 $profile = APContact::getByURL($actor);
628 $followers = $profile['followers'] ?? '';
630 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
632 Logger::info('Empty actor', ['activity' => $activity]);
636 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
637 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
638 if (empty($receiver_list)) {
642 foreach ($receiver_list as $receiver) {
643 if ($receiver == self::PUBLIC_COLLECTION) {
644 $receivers['uid:0'] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
647 // Add receiver "-1" for unlisted posts
648 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
649 $receivers['uid:-1'] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
652 // Fetch the receivers for the public and the followers collection
653 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
654 $receivers = self::getReceiverForActor($actor, $tags, $receivers);
658 // Fetching all directly addressed receivers
659 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
660 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
661 if (!DBA::isResult($contact)) {
665 // Check if the potential receiver is following the actor
666 // Exception: The receiver is targetted via "to" or this is a comment
667 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
668 $networks = Protocol::FEDERATED;
669 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
670 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
672 // Forum posts are only accepted from forum contacts
673 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
674 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
677 if (!DBA::exists('contact', $condition)) {
682 $type = $receivers['uid:' . $contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
683 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
686 $type = self::TARGET_TO;
689 $type = self::TARGET_CC;
692 $type = self::TARGET_BTO;
695 $type = self::TARGET_BCC;
699 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
704 self::switchContacts($receivers, $actor);
710 * Fetch the receiver list of a given actor
712 * @param string $actor
715 * @return array with receivers (user id)
718 private static function getReceiverForActor($actor, $tags, $receivers)
720 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
721 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
723 $condition = DBA::mergeConditions($basecondition, ['nurl' => Strings::normaliseLink($actor)]);
724 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
725 while ($contact = DBA::fetch($contacts)) {
726 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
727 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
730 DBA::close($contacts);
732 // The queries are split because of performance issues
733 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?)", Strings::normaliseLink($actor), $actor]);
734 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
735 while ($contact = DBA::fetch($contacts)) {
736 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
737 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
740 DBA::close($contacts);
745 * Tests if the contact is a valid receiver for this actor
747 * @param array $contact
748 * @param string $actor
751 * @return bool with receivers (user id)
754 private static function isValidReceiverForActor($contact, $actor, $tags)
756 // Public contacts are no valid receiver
757 if ($contact['uid'] == 0) {
761 // Are we following the contact? Then this is a valid receiver
762 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
766 // When the possible receiver isn't a community, then it is no valid receiver
767 $owner = User::getOwnerDataById($contact['uid']);
768 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
772 // Is the community account tagged?
773 foreach ($tags as $tag) {
774 if ($tag['type'] != 'Mention') {
778 if ($tag['href'] == $owner['url']) {
787 * Switches existing contacts to ActivityPub
789 * @param integer $cid Contact ID
790 * @param integer $uid User ID
791 * @param string $url Profile URL
792 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
793 * @throws \ImagickException
795 public static function switchContact($cid, $uid, $url)
797 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
798 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
802 if (Contact::updateFromProbe($cid)) {
803 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
806 // Send a new follow request to be sure that the connection still exists
807 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
808 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
809 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
819 * @throws \ImagickException
821 private static function switchContacts($receivers, $actor)
827 foreach ($receivers as $receiver) {
828 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
829 if (DBA::isResult($contact)) {
830 self::switchContact($contact['id'], $receiver['uid'], $actor);
833 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
834 if (DBA::isResult($contact)) {
835 self::switchContact($contact['id'], $receiver['uid'], $actor);
843 * @param $object_data
844 * @param array $activity
848 private static function addActivityFields($object_data, $activity)
850 if (!empty($activity['published']) && empty($object_data['published'])) {
851 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
854 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
855 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
858 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
859 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
861 if (!empty($object_data['object_id'])) {
862 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
863 $objectId = Item::getURIByLink($object_data['object_id']);
864 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
865 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
866 $object_data['object_id'] = $objectId;
874 * Fetches the object data from external ressources if needed
876 * @param string $object_id Object ID of the the provided object
877 * @param array $object The provided object array
878 * @param boolean $trust_source Do we trust the provided object?
879 * @param integer $uid User ID for the signature that we use to fetch data
881 * @return array|false with trusted and valid object data
882 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
883 * @throws \ImagickException
885 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
887 // By fetching the type we check if the object is complete.
888 $type = JsonLD::fetchElement($object, '@type');
890 if (!$trust_source || empty($type)) {
891 $data = ActivityPub::fetchContent($object_id, $uid);
893 $object = JsonLD::compact($data);
894 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
896 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
898 $item = Item::selectFirst([], ['uri' => $object_id]);
899 if (!DBA::isResult($item)) {
900 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
903 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
904 $data = ActivityPub\Transmitter::createNote($item);
905 $object = JsonLD::compact($data);
908 $id = JsonLD::fetchElement($object, '@id');
910 Logger::info('Empty id');
914 if ($id != $object_id) {
915 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
919 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
922 $type = JsonLD::fetchElement($object, '@type');
924 Logger::info('Empty type');
928 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
929 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
930 $object_data = self::processObject($object);
933 $object_data['raw'] = json_encode($data);
938 if ($type == 'as:Announce') {
939 $object_id = JsonLD::fetchElement($object, 'object', '@id');
940 if (empty($object_id) || !is_string($object_id)) {
943 return self::fetchObject($object_id, [], false, $uid);
946 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
951 * Convert tags from JSON-LD format into a simplified format
953 * @param array $tags Tags in JSON-LD format
955 * @return array with tags in a simplified format
957 private static function processTags(array $tags)
961 foreach ($tags as $tag) {
966 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
967 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
968 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
970 if (empty($element['type'])) {
974 if (empty($element['href'])) {
975 $element['href'] = $element['name'];
978 $taglist[] = $element;
984 * Convert emojis from JSON-LD format into a simplified format
986 * @param array $emojis
987 * @return array with emojis in a simplified format
989 private static function processEmojis(array $emojis)
993 foreach ($emojis as $emoji) {
994 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
998 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
999 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1002 $emojilist[] = $element;
1009 * Convert attachments from JSON-LD format into a simplified format
1011 * @param array $attachments Attachments in JSON-LD format
1013 * @return array Attachments in a simplified format
1015 private static function processAttachments(array $attachments)
1019 // Removes empty values
1020 $attachments = array_filter($attachments);
1022 foreach ($attachments as $attachment) {
1023 switch (JsonLD::fetchElement($attachment, '@type')) {
1028 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1029 foreach ($urls as $url) {
1030 // Single scalar URL case
1031 if (is_string($url)) {
1036 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1037 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1038 if (Strings::startsWith($mediaType, 'image')) {
1047 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1048 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1050 'image' => $pageImage,
1055 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1056 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1057 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1058 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1062 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1063 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1064 $imagePreviewUrl = null;
1066 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1067 $imageVariants = [];
1068 $previewVariants = [];
1069 foreach ($urls as $url) {
1070 // Scalar URL, no discrimination possible
1071 if (is_string($url)) {
1072 $imageFullUrl = $url;
1076 // Not sure what to do with a different Link media type than the base Image, we skip
1077 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1081 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1083 // Default URL choice if no discriminating width is provided
1084 $imageFullUrl = $href ?? $imageFullUrl;
1086 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1088 if ($href && $width) {
1089 $imageVariants[$width] = $href;
1090 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1091 $previewVariants[abs(632 - $width)] = $href;
1095 if ($imageVariants) {
1096 // Taking the maximum size image
1097 ksort($imageVariants);
1098 $imageFullUrl = array_pop($imageVariants);
1100 // Taking the minimum number distance to the target distance
1101 ksort($previewVariants);
1102 $imagePreviewUrl = array_shift($previewVariants);
1105 unset($imageVariants);
1106 unset($previewVariants);
1110 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1111 'mediaType' => $mediaType,
1112 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1113 'url' => $imageFullUrl,
1114 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1119 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1120 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1121 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1122 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1131 * Fetch the original source or content with the "language" Markdown or HTML
1133 * @param array $object
1134 * @param array $object_data
1137 * @throws \Exception
1139 private static function getSource($object, $object_data)
1141 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1142 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1143 if (!empty($object_data['source'])) {
1144 return $object_data;
1147 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1148 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1149 if (!empty($object_data['source'])) {
1150 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1151 return $object_data;
1154 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1155 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1156 if (!empty($object_data['source'])) {
1157 $object_data['source'] = HTML::toBBCode($object_data['source']);
1158 return $object_data;
1161 return $object_data;
1165 * Check if the "as:url" element is an array with multiple links
1166 * This is the case with audio and video posts.
1167 * Then the links are added as attachments
1169 * @param array $object The raw object
1170 * @param array $object_data The parsed object data for later processing
1171 * @return array the object data
1173 private static function processAttachmentUrls(array $object, array $object_data) {
1174 // Check if this is some url with multiple links
1175 if (empty($object['as:url'])) {
1176 return $object_data;
1179 $urls = $object['as:url'];
1180 $keys = array_keys($urls);
1181 if (!is_numeric(array_pop($keys))) {
1182 return $object_data;
1187 foreach ($urls as $url) {
1188 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1192 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1197 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1198 if (empty($mediatype)) {
1202 if ($mediatype == 'text/html') {
1203 $object_data['alternate-url'] = $href;
1206 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1208 if ($filetype == 'audio') {
1209 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1210 } elseif ($filetype == 'video') {
1211 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1213 // We save bandwidth by using a moderate height
1214 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1215 if (!empty($attachments[$filetype]['height']) &&
1216 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1220 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1224 foreach ($attachments as $type => $attachment) {
1225 $object_data['attachments'][] = ['type' => $type,
1226 'mediaType' => $attachment['type'],
1228 'url' => $attachment['url']];
1230 return $object_data;
1234 * Fetches data from the object part of an activity
1236 * @param array $object
1239 * @throws \Exception
1241 private static function processObject($object)
1243 if (!JsonLD::fetchElement($object, '@id')) {
1248 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1249 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1250 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1252 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1253 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1254 $object_data['reply-to-id'] = $object_data['id'];
1256 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1257 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1258 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1259 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1260 $object_data['reply-to-id'] = $replyToId;
1264 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1265 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1267 if (empty($object_data['updated'])) {
1268 $object_data['updated'] = $object_data['published'];
1271 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1272 $object_data['published'] = $object_data['updated'];
1275 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1276 if (empty($actor)) {
1277 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1280 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1281 $location = JsonLD::fetchElement($location, 'location', '@value');
1283 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1284 // down to HTML and then finally format to plaintext.
1285 $location = Markdown::convert($location);
1286 $location = BBCode::convert($location);
1287 $location = HTML::toPlaintext($location);
1290 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1291 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1292 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1293 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1294 $object_data['actor'] = $object_data['author'] = $actor;
1295 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1296 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1297 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1298 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1299 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1300 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1301 $object_data = self::getSource($object, $object_data);
1302 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1303 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1304 $object_data['location'] = $location;
1305 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1306 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1307 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1308 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1309 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1310 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1311 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1312 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1313 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1314 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1316 // Special treatment for Hubzilla links
1317 if (is_array($object_data['alternate-url'])) {
1318 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1320 if (!is_string($object_data['alternate-url'])) {
1321 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1325 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1326 $object_data = self::processAttachmentUrls($object, $object_data);
1329 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1330 $receivers = $reception_types = [];
1331 foreach ($receiverdata as $key => $data) {
1332 $receivers[$key] = $data['uid'];
1333 $reception_types[$data['uid']] = $data['type'] ?? 0;
1336 $object_data['receiver'] = $receivers;
1337 $object_data['reception_type'] = $reception_types;
1339 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1340 unset($object_data['receiver']['uid:-1']);
1342 // Common object data:
1345 // @context, type, actor, signature, mediaType, duration, replies, icon
1347 // Also missing: (Defined in the standard, but currently unused)
1348 // audience, preview, endTime, startTime, image
1353 // contentMap, announcement_count, announcements, context_id, likes, like_count
1354 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1359 // category, licence, language, commentsEnabled
1362 // views, waitTranscoding, state, support, subtitleLanguage
1363 // likes, dislikes, shares, comments
1365 return $object_data;