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;
70 * Checks if the web request is done for the AP protocol
72 * @return bool is it AP?
74 public static function isRequest()
76 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
77 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
81 * Checks incoming message from the inbox
85 * @param integer $uid User ID
88 public static function processInbox($body, $header, $uid)
90 $http_signer = HTTPSignature::getSigner($body, $header);
91 if (empty($http_signer)) {
92 Logger::warning('Invalid HTTP signature, message will be discarded.');
95 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
98 $signer = [$http_signer];
99 $activity = json_decode($body, true);
101 if (empty($activity)) {
102 Logger::warning('Invalid body.');
106 $ldactivity = JsonLD::compact($activity);
108 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
110 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
112 if (LDSignature::isSigned($activity)) {
113 $ld_signer = LDSignature::getSigner($activity);
114 if (empty($ld_signer)) {
115 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
116 } elseif ($ld_signer != $http_signer) {
117 $signer[] = $ld_signer;
119 if (!empty($ld_signer && ($actor == $http_signer))) {
120 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
121 $trust_source = true;
122 } elseif (!empty($ld_signer)) {
123 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
124 $trust_source = true;
125 } elseif ($actor == $http_signer) {
126 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
127 $trust_source = true;
129 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
130 $trust_source = false;
132 } elseif ($actor == $http_signer) {
133 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
134 $trust_source = true;
136 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
137 $trust_source = false;
140 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
144 * Fetches the object type for a given object id
146 * @param array $activity
147 * @param string $object_id Object ID of the the provided object
148 * @param integer $uid User ID
150 * @return string with object type
151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
152 * @throws \ImagickException
154 private static function fetchObjectType($activity, $object_id, $uid = 0)
156 if (!empty($activity['as:object'])) {
157 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
158 if (!empty($object_type)) {
163 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
164 // We just assume "note" since it doesn't make a difference for the further processing
168 $profile = APContact::getByURL($object_id);
169 if (!empty($profile['type'])) {
170 return 'as:' . $profile['type'];
173 $data = ActivityPub::fetchContent($object_id, $uid);
175 $object = JsonLD::compact($data);
176 $type = JsonLD::fetchElement($object, '@type');
186 * Prepare the object array
188 * @param array $activity Array with activity data
189 * @param integer $uid User ID
190 * @param boolean $push Message had been pushed to our system
191 * @param boolean $trust_source Do we trust the source?
193 * @return array with object data
194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
195 * @throws \ImagickException
197 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
199 $id = JsonLD::fetchElement($activity, '@id');
200 if (!empty($id) && !$trust_source) {
201 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
202 if (!empty($fetched_activity)) {
203 $object = JsonLD::compact($fetched_activity);
204 $fetched_id = JsonLD::fetchElement($object, '@id');
205 if ($fetched_id == $id) {
206 Logger::info('Activity had been fetched successfully', ['id' => $id]);
207 $trust_source = true;
210 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
213 Logger::info('Activity could not been fetched', ['id' => $id]);
217 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
219 Logger::info('Empty actor', ['activity' => $activity]);
223 $type = JsonLD::fetchElement($activity, '@type');
225 // Fetch all receivers from to, cc, bto and bcc
226 $receiverdata = self::getReceivers($activity, $actor);
227 $receivers = $reception_types = [];
228 foreach ($receiverdata as $key => $data) {
229 $receivers[$key] = $data['uid'];
230 $reception_types[$data['uid']] = $data['type'] ?? 0;
233 // When it is a delivery to a personal inbox we add that user to the receivers
235 $additional = ['uid:' . $uid => $uid];
236 $receivers = array_merge($receivers, $additional);
237 if (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER])) {
238 $reception_types[$uid] = self::TARGET_BCC;
241 // We possibly need some user to fetch private content,
242 // so we fetch the first out ot the list.
243 $uid = self::getFirstUserFromReceivers($receivers);
246 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
247 if (empty($object_id)) {
248 Logger::log('No object found', Logger::DEBUG);
252 if (!is_string($object_id)) {
253 Logger::info('Invalid object id', ['object' => $object_id]);
257 $object_type = self::fetchObjectType($activity, $object_id, $uid);
259 // Fetch the content only on activities where this matters
260 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
261 // Always fetch on "Announce"
262 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
263 if (empty($object_data)) {
264 Logger::log("Object data couldn't be processed", Logger::DEBUG);
268 $object_data['object_id'] = $object_id;
270 if ($type == 'as:Announce') {
271 $object_data['push'] = false;
273 $object_data['push'] = $push;
276 // Test if it is an answer to a mail
277 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
278 $object_data['directmessage'] = true;
280 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
282 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
283 // Create a mostly empty array out of the activity data (instead of the object).
284 // This way we later don't have to check for the existence of ech individual array element.
285 $object_data = self::processObject($activity);
286 $object_data['name'] = $type;
287 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
288 $object_data['object_id'] = $object_id;
289 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
290 } elseif (in_array($type, ['as:Add'])) {
292 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
293 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
294 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
295 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
296 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
299 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
300 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
301 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
302 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
303 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
305 // An Undo is done on the object of an object, so we need that type as well
306 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
307 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
311 $object_data = self::addActivityFields($object_data, $activity);
313 if (empty($object_data['object_type'])) {
314 $object_data['object_type'] = $object_type;
317 $object_data['type'] = $type;
318 $object_data['actor'] = $actor;
319 $object_data['item_receiver'] = $receivers;
320 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
321 $object_data['reception_type'] = array_merge($object_data['reception_type'] ?? [], $reception_types);
323 $author = $object_data['author'] ?? $actor;
324 if (!empty($author) && !empty($object_data['id'])) {
325 $author_host = parse_url($author, PHP_URL_HOST);
326 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
327 if ($author_host == $id_host) {
328 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
330 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
331 $trust_source = false;
335 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
341 * Fetches the first user id from the receiver array
343 * @param array $receivers Array with receivers
344 * @return integer user id;
346 public static function getFirstUserFromReceivers($receivers)
348 foreach ($receivers as $receiver) {
349 if (!empty($receiver)) {
357 * Processes the activity object
359 * @param array $activity Array with activity data
360 * @param string $body
361 * @param integer $uid User ID
362 * @param boolean $trust_source Do we trust the source?
363 * @param boolean $push Message had been pushed to our system
366 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
368 $type = JsonLD::fetchElement($activity, '@type');
370 Logger::info('Empty type', ['activity' => $activity]);
374 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
375 Logger::info('Empty object', ['activity' => $activity]);
379 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
381 Logger::info('Empty actor', ['activity' => $activity]);
385 if (is_array($activity['as:object'])) {
386 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
391 // Test the provided signatures against the actor and "attributedTo"
393 if (!empty($attributed_to) && !empty($actor)) {
394 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
396 $trust_source = in_array($actor, $signer);
400 // $trust_source is called by reference and is set to true if the content was retrieved successfully
401 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
402 if (empty($object_data)) {
403 Logger::info('No object data found', ['activity' => $activity]);
407 if (!$trust_source) {
408 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
412 if (!empty($body) && empty($object_data['raw'])) {
413 $object_data['raw'] = $body;
416 // Internal flag for thread completion. See Processor.php
417 if (!empty($activity['thread-completion'])) {
418 $object_data['thread-completion'] = $activity['thread-completion'];
423 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
424 $item = ActivityPub\Processor::createItem($object_data);
425 ActivityPub\Processor::postItem($object_data, $item);
430 if ($object_data['object_type'] == 'as:tag') {
431 ActivityPub\Processor::addTag($object_data);
436 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
437 $object_data['thread-completion'] = true;
439 $item = ActivityPub\Processor::createItem($object_data);
440 ActivityPub\Processor::postItem($object_data, $item);
442 $announce_object_data = self::processObject($activity);
443 $announce_object_data['name'] = $type;
444 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
445 $announce_object_data['object_id'] = $object_data['object_id'];
446 $announce_object_data['object_type'] = $object_data['object_type'];
447 $announce_object_data['push'] = $push;
450 $announce_object_data['raw'] = $body;
453 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
458 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
459 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
464 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
465 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
469 case 'as:TentativeAccept':
470 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
471 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
476 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
477 ActivityPub\Processor::updateItem($object_data);
478 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
479 ActivityPub\Processor::updatePerson($object_data);
484 if ($object_data['object_type'] == 'as:Tombstone') {
485 ActivityPub\Processor::deleteItem($object_data);
486 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
487 ActivityPub\Processor::deletePerson($object_data);
492 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
493 ActivityPub\Processor::followUser($object_data);
494 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
495 $object_data['reply-to-id'] = $object_data['object_id'];
496 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
501 if ($object_data['object_type'] == 'as:Follow') {
502 ActivityPub\Processor::acceptFollowUser($object_data);
503 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
504 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
509 if ($object_data['object_type'] == 'as:Follow') {
510 ActivityPub\Processor::rejectFollowUser($object_data);
511 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
512 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
517 if (($object_data['object_type'] == 'as:Follow') &&
518 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
519 ActivityPub\Processor::undoFollowUser($object_data);
520 } elseif (($object_data['object_type'] == 'as:Accept') &&
521 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
522 ActivityPub\Processor::rejectFollowUser($object_data);
523 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
524 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
525 ActivityPub\Processor::undoActivity($object_data);
530 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
536 * Fetch the receiver list from an activity array
538 * @param array $activity
539 * @param string $actor
541 * @param boolean $fetch_unlisted
543 * @return array with receivers (user id)
546 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
548 $reply = $receivers = [];
550 // When it is an answer, we inherite the receivers from the parent
551 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
552 if (!empty($replyto)) {
555 // Fix possibly wrong item URI (could be an answer to a plink uri)
556 $fixedReplyTo = Item::getURIByLink($replyto);
557 if (!empty($fixedReplyTo)) {
558 $reply[] = $fixedReplyTo;
562 // Fetch all posts that refer to the object id
563 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
564 if (!empty($object_id)) {
565 $reply[] = $object_id;
568 if (!empty($reply)) {
569 $parents = Item::select(['uid'], ['uri' => $reply]);
570 while ($parent = Item::fetch($parents)) {
571 $receivers['uid:' . $parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
575 if (!empty($actor)) {
576 $profile = APContact::getByURL($actor);
577 $followers = $profile['followers'] ?? '';
579 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
581 Logger::info('Empty actor', ['activity' => $activity]);
585 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
586 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
587 if (empty($receiver_list)) {
591 foreach ($receiver_list as $receiver) {
592 if ($receiver == self::PUBLIC_COLLECTION) {
593 $receivers['uid:0'] = ['uid' => 0, 'type' => self::TARGET_UNKNOWN];
596 // Add receiver "-1" for unlisted posts
597 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
598 $receivers['uid:-1'] = ['uid' => -1, 'type' => self::TARGET_UNKNOWN];
601 // Fetch the receivers for the public and the followers collection
602 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
603 $receivers = self::getReceiverForActor($actor, $tags, $receivers);
607 // Fetching all directly addressed receivers
608 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
609 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
610 if (!DBA::isResult($contact)) {
614 // Check if the potential receiver is following the actor
615 // Exception: The receiver is targetted via "to" or this is a comment
616 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
617 $networks = Protocol::FEDERATED;
618 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
619 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
621 // Forum posts are only accepted from forum contacts
622 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
623 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
626 if (!DBA::exists('contact', $condition)) {
631 $type = $receivers['uid:' . $contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
632 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER])) {
635 $type = self::TARGET_TO;
638 $type = self::TARGET_CC;
641 $type = self::TARGET_BTO;
644 $type = self::TARGET_BCC;
648 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
653 self::switchContacts($receivers, $actor);
659 * Fetch the receiver list of a given actor
661 * @param string $actor
664 * @return array with receivers (user id)
667 private static function getReceiverForActor($actor, $tags, $receivers)
669 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
670 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
672 $condition = DBA::mergeConditions($basecondition, ['nurl' => Strings::normaliseLink($actor)]);
673 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
674 while ($contact = DBA::fetch($contacts)) {
675 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
676 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
679 DBA::close($contacts);
681 // The queries are split because of performance issues
682 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?)", Strings::normaliseLink($actor), $actor]);
683 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
684 while ($contact = DBA::fetch($contacts)) {
685 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
686 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
689 DBA::close($contacts);
694 * Tests if the contact is a valid receiver for this actor
696 * @param array $contact
697 * @param string $actor
700 * @return bool with receivers (user id)
703 private static function isValidReceiverForActor($contact, $actor, $tags)
705 // Public contacts are no valid receiver
706 if ($contact['uid'] == 0) {
710 // Are we following the contact? Then this is a valid receiver
711 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
715 // When the possible receiver isn't a community, then it is no valid receiver
716 $owner = User::getOwnerDataById($contact['uid']);
717 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
721 // Is the community account tagged?
722 foreach ($tags as $tag) {
723 if ($tag['type'] != 'Mention') {
727 if ($tag['href'] == $owner['url']) {
736 * Switches existing contacts to ActivityPub
738 * @param integer $cid Contact ID
739 * @param integer $uid User ID
740 * @param string $url Profile URL
741 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
742 * @throws \ImagickException
744 public static function switchContact($cid, $uid, $url)
746 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
747 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
751 if (Contact::updateFromProbe($cid)) {
752 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
755 // Send a new follow request to be sure that the connection still exists
756 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
757 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
758 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
767 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
768 * @throws \ImagickException
770 private static function switchContacts($receivers, $actor)
776 foreach ($receivers as $receiver) {
777 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
778 if (DBA::isResult($contact)) {
779 self::switchContact($contact['id'], $receiver['uid'], $actor);
782 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
783 if (DBA::isResult($contact)) {
784 self::switchContact($contact['id'], $receiver['uid'], $actor);
792 * @param $object_data
793 * @param array $activity
797 private static function addActivityFields($object_data, $activity)
799 if (!empty($activity['published']) && empty($object_data['published'])) {
800 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
803 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
804 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
807 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
808 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
810 if (!empty($object_data['object_id'])) {
811 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
812 $objectId = Item::getURIByLink($object_data['object_id']);
813 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
814 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
815 $object_data['object_id'] = $objectId;
823 * Fetches the object data from external ressources if needed
825 * @param string $object_id Object ID of the the provided object
826 * @param array $object The provided object array
827 * @param boolean $trust_source Do we trust the provided object?
828 * @param integer $uid User ID for the signature that we use to fetch data
830 * @return array|false with trusted and valid object data
831 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
832 * @throws \ImagickException
834 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
836 // By fetching the type we check if the object is complete.
837 $type = JsonLD::fetchElement($object, '@type');
839 if (!$trust_source || empty($type)) {
840 $data = ActivityPub::fetchContent($object_id, $uid);
842 $object = JsonLD::compact($data);
843 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
845 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
847 $item = Item::selectFirst([], ['uri' => $object_id]);
848 if (!DBA::isResult($item)) {
849 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
852 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
853 $data = ActivityPub\Transmitter::createNote($item);
854 $object = JsonLD::compact($data);
857 $id = JsonLD::fetchElement($object, '@id');
859 Logger::info('Empty id');
863 if ($id != $object_id) {
864 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
868 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
871 $type = JsonLD::fetchElement($object, '@type');
873 Logger::info('Empty type');
877 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
878 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
879 $object_data = self::processObject($object);
882 $object_data['raw'] = json_encode($data);
887 if ($type == 'as:Announce') {
888 $object_id = JsonLD::fetchElement($object, 'object', '@id');
889 if (empty($object_id) || !is_string($object_id)) {
892 return self::fetchObject($object_id, [], false, $uid);
895 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
900 * Convert tags from JSON-LD format into a simplified format
902 * @param array $tags Tags in JSON-LD format
904 * @return array with tags in a simplified format
906 private static function processTags(array $tags)
910 foreach ($tags as $tag) {
915 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
916 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
917 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
919 if (empty($element['type'])) {
923 if (empty($element['href'])) {
924 $element['href'] = $element['name'];
927 $taglist[] = $element;
933 * Convert emojis from JSON-LD format into a simplified format
935 * @param array $emojis
936 * @return array with emojis in a simplified format
938 private static function processEmojis(array $emojis)
942 foreach ($emojis as $emoji) {
943 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
947 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
948 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
951 $emojilist[] = $element;
958 * Convert attachments from JSON-LD format into a simplified format
960 * @param array $attachments Attachments in JSON-LD format
962 * @return array Attachments in a simplified format
964 private static function processAttachments(array $attachments)
968 // Removes empty values
969 $attachments = array_filter($attachments);
971 foreach ($attachments as $attachment) {
972 switch (JsonLD::fetchElement($attachment, '@type')) {
977 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
978 foreach ($urls as $url) {
979 // Single scalar URL case
980 if (is_string($url)) {
985 $href = JsonLD::fetchElement($url, 'as:href', '@id');
986 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
987 if (Strings::startsWith($mediaType, 'image')) {
996 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
997 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
999 'image' => $pageImage,
1004 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1005 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1006 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1007 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1011 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1012 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1013 $imagePreviewUrl = null;
1015 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1016 $imageVariants = [];
1017 $previewVariants = [];
1018 foreach ($urls as $url) {
1019 // Scalar URL, no discrimination possible
1020 if (is_string($url)) {
1021 $imageFullUrl = $url;
1025 // Not sure what to do with a different Link media type than the base Image, we skip
1026 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1030 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1032 // Default URL choice if no discriminating width is provided
1033 $imageFullUrl = $href ?? $imageFullUrl;
1035 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1037 if ($href && $width) {
1038 $imageVariants[$width] = $href;
1039 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1040 $previewVariants[abs(632 - $width)] = $href;
1044 if ($imageVariants) {
1045 // Taking the maximum size image
1046 ksort($imageVariants);
1047 $imageFullUrl = array_pop($imageVariants);
1049 // Taking the minimum number distance to the target distance
1050 ksort($previewVariants);
1051 $imagePreviewUrl = array_shift($previewVariants);
1054 unset($imageVariants);
1055 unset($previewVariants);
1059 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1060 'mediaType' => $mediaType,
1061 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1062 'url' => $imageFullUrl,
1063 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1068 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1069 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1070 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1071 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1080 * Fetch the original source or content with the "language" Markdown or HTML
1082 * @param array $object
1083 * @param array $object_data
1086 * @throws \Exception
1088 private static function getSource($object, $object_data)
1090 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1091 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1092 if (!empty($object_data['source'])) {
1093 return $object_data;
1096 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1097 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1098 if (!empty($object_data['source'])) {
1099 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1100 return $object_data;
1103 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1104 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1105 if (!empty($object_data['source'])) {
1106 $object_data['source'] = HTML::toBBCode($object_data['source']);
1107 return $object_data;
1110 return $object_data;
1114 * Check if the "as:url" element is an array with multiple links
1115 * This is the case with audio and video posts.
1116 * Then the links are added as attachments
1118 * @param array $object The raw object
1119 * @param array $object_data The parsed object data for later processing
1120 * @return array the object data
1122 private static function processAttachmentUrls(array $object, array $object_data) {
1123 // Check if this is some url with multiple links
1124 if (empty($object['as:url'])) {
1125 return $object_data;
1128 $urls = $object['as:url'];
1129 $keys = array_keys($urls);
1130 if (!is_numeric(array_pop($keys))) {
1131 return $object_data;
1136 foreach ($urls as $url) {
1137 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1141 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1146 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1147 if (empty($mediatype)) {
1151 if ($mediatype == 'text/html') {
1152 $object_data['alternate-url'] = $href;
1155 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1157 if ($filetype == 'audio') {
1158 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1159 } elseif ($filetype == 'video') {
1160 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1162 // We save bandwidth by using a moderate height
1163 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1164 if (!empty($attachments[$filetype]['height']) &&
1165 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1169 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1173 foreach ($attachments as $type => $attachment) {
1174 $object_data['attachments'][] = ['type' => $type,
1175 'mediaType' => $attachment['type'],
1177 'url' => $attachment['url']];
1179 return $object_data;
1183 * Fetches data from the object part of an activity
1185 * @param array $object
1188 * @throws \Exception
1190 private static function processObject($object)
1192 if (!JsonLD::fetchElement($object, '@id')) {
1197 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1198 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1199 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1201 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1202 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1203 $object_data['reply-to-id'] = $object_data['id'];
1205 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1206 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1207 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1208 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1209 $object_data['reply-to-id'] = $replyToId;
1213 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1214 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1216 if (empty($object_data['updated'])) {
1217 $object_data['updated'] = $object_data['published'];
1220 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1221 $object_data['published'] = $object_data['updated'];
1224 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1225 if (empty($actor)) {
1226 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1229 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1230 $location = JsonLD::fetchElement($location, 'location', '@value');
1232 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1233 // down to HTML and then finally format to plaintext.
1234 $location = Markdown::convert($location);
1235 $location = BBCode::convert($location);
1236 $location = HTML::toPlaintext($location);
1239 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1240 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1241 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1242 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1243 $object_data['actor'] = $object_data['author'] = $actor;
1244 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1245 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1246 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1247 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1248 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1249 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1250 $object_data = self::getSource($object, $object_data);
1251 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1252 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1253 $object_data['location'] = $location;
1254 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1255 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1256 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1257 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1258 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1259 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1260 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1261 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1262 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1263 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1265 // Special treatment for Hubzilla links
1266 if (is_array($object_data['alternate-url'])) {
1267 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1269 if (!is_string($object_data['alternate-url'])) {
1270 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1274 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1275 $object_data = self::processAttachmentUrls($object, $object_data);
1278 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1279 $receivers = $reception_types = [];
1280 foreach ($receiverdata as $key => $data) {
1281 $receivers[$key] = $data['uid'];
1282 $reception_types[$data['uid']] = $data['type'] ?? 0;
1285 $object_data['receiver'] = $receivers;
1286 $object_data['reception_type'] = $reception_types;
1288 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1289 unset($object_data['receiver']['uid:-1']);
1291 // Common object data:
1294 // @context, type, actor, signature, mediaType, duration, replies, icon
1296 // Also missing: (Defined in the standard, but currently unused)
1297 // audience, preview, endTime, startTime, image
1302 // contentMap, announcement_count, announcements, context_id, likes, like_count
1303 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1308 // category, licence, language, commentsEnabled
1311 // views, waitTranscoding, state, support, subtitleLanguage
1312 // likes, dislikes, shares, comments
1314 return $object_data;