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 $http_signer = HTTPSignature::getSigner($body, $header);
92 if (empty($http_signer)) {
93 Logger::warning('Invalid HTTP signature, message will be discarded.');
96 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
99 $signer = [$http_signer];
100 $activity = json_decode($body, true);
102 if (empty($activity)) {
103 Logger::warning('Invalid body.');
107 $ldactivity = JsonLD::compact($activity);
109 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
111 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
113 if (LDSignature::isSigned($activity)) {
114 $ld_signer = LDSignature::getSigner($activity);
115 if (empty($ld_signer)) {
116 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
117 } elseif ($ld_signer != $http_signer) {
118 $signer[] = $ld_signer;
120 if (!empty($ld_signer && ($actor == $http_signer))) {
121 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
122 $trust_source = true;
123 } elseif (!empty($ld_signer)) {
124 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
125 $trust_source = true;
126 } elseif ($actor == $http_signer) {
127 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
128 $trust_source = true;
130 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
131 $trust_source = false;
133 } elseif ($actor == $http_signer) {
134 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
135 $trust_source = true;
137 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
138 $trust_source = false;
141 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
145 * Fetches the object type for a given object id
147 * @param array $activity
148 * @param string $object_id Object ID of the the provided object
149 * @param integer $uid User ID
151 * @return string with object type
152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
153 * @throws \ImagickException
155 private static function fetchObjectType($activity, $object_id, $uid = 0)
157 if (!empty($activity['as:object'])) {
158 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
159 if (!empty($object_type)) {
164 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
165 // We just assume "note" since it doesn't make a difference for the further processing
169 $profile = APContact::getByURL($object_id);
170 if (!empty($profile['type'])) {
171 return 'as:' . $profile['type'];
174 $data = ActivityPub::fetchContent($object_id, $uid);
176 $object = JsonLD::compact($data);
177 $type = JsonLD::fetchElement($object, '@type');
187 * Prepare the object array
189 * @param array $activity Array with activity data
190 * @param integer $uid User ID
191 * @param boolean $push Message had been pushed to our system
192 * @param boolean $trust_source Do we trust the source?
194 * @return array with object data
195 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
196 * @throws \ImagickException
198 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
200 $id = JsonLD::fetchElement($activity, '@id');
201 if (!empty($id) && !$trust_source) {
202 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
203 if (!empty($fetched_activity)) {
204 $object = JsonLD::compact($fetched_activity);
205 $fetched_id = JsonLD::fetchElement($object, '@id');
206 if ($fetched_id == $id) {
207 Logger::info('Activity had been fetched successfully', ['id' => $id]);
208 $trust_source = true;
211 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
214 Logger::info('Activity could not been fetched', ['id' => $id]);
218 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
220 Logger::info('Empty actor', ['activity' => $activity]);
224 $type = JsonLD::fetchElement($activity, '@type');
226 // Fetch all receivers from to, cc, bto and bcc
227 $receiverdata = self::getReceivers($activity, $actor);
228 $receivers = $reception_types = [];
229 foreach ($receiverdata as $key => $data) {
230 $receivers[$key] = $data['uid'];
231 $reception_types[$data['uid']] = $data['type'] ?? 0;
234 // When it is a delivery to a personal inbox we add that user to the receivers
236 $additional = ['uid:' . $uid => $uid];
237 $receivers = array_merge($receivers, $additional);
238 if (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
239 $reception_types[$uid] = self::TARGET_BCC;
242 // We possibly need some user to fetch private content,
243 // so we fetch the first out ot the list.
244 $uid = self::getFirstUserFromReceivers($receivers);
247 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
248 if (empty($object_id)) {
249 Logger::log('No object found', Logger::DEBUG);
253 if (!is_string($object_id)) {
254 Logger::info('Invalid object id', ['object' => $object_id]);
258 $object_type = self::fetchObjectType($activity, $object_id, $uid);
260 // Fetch the content only on activities where this matters
261 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
262 // Always fetch on "Announce"
263 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
264 if (empty($object_data)) {
265 Logger::log("Object data couldn't be processed", Logger::DEBUG);
269 $object_data['object_id'] = $object_id;
271 if ($type == 'as:Announce') {
272 $object_data['push'] = false;
274 $object_data['push'] = $push;
277 // Test if it is an answer to a mail
278 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
279 $object_data['directmessage'] = true;
281 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
283 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
284 // Create a mostly empty array out of the activity data (instead of the object).
285 // This way we later don't have to check for the existence of ech individual array element.
286 $object_data = self::processObject($activity);
287 $object_data['name'] = $type;
288 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
289 $object_data['object_id'] = $object_id;
290 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
291 } elseif (in_array($type, ['as:Add'])) {
293 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
294 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
295 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
296 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
297 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
300 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
301 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
302 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
303 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
304 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
306 // An Undo is done on the object of an object, so we need that type as well
307 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
308 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
312 $object_data = self::addActivityFields($object_data, $activity);
314 if (empty($object_data['object_type'])) {
315 $object_data['object_type'] = $object_type;
318 $object_data['type'] = $type;
319 $object_data['actor'] = $actor;
320 $object_data['item_receiver'] = $receivers;
321 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
322 $object_data['reception_type'] = array_merge($object_data['reception_type'] ?? [], $reception_types);
324 $author = $object_data['author'] ?? $actor;
325 if (!empty($author) && !empty($object_data['id'])) {
326 $author_host = parse_url($author, PHP_URL_HOST);
327 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
328 if ($author_host == $id_host) {
329 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
331 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
332 $trust_source = false;
336 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
342 * Fetches the first user id from the receiver array
344 * @param array $receivers Array with receivers
345 * @return integer user id;
347 public static function getFirstUserFromReceivers($receivers)
349 foreach ($receivers as $receiver) {
350 if (!empty($receiver)) {
358 * Processes the activity object
360 * @param array $activity Array with activity data
361 * @param string $body
362 * @param integer $uid User ID
363 * @param boolean $trust_source Do we trust the source?
364 * @param boolean $push Message had been pushed to our system
367 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
369 $type = JsonLD::fetchElement($activity, '@type');
371 Logger::info('Empty type', ['activity' => $activity]);
375 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
376 Logger::info('Empty object', ['activity' => $activity]);
380 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
382 Logger::info('Empty actor', ['activity' => $activity]);
386 if (is_array($activity['as:object'])) {
387 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
392 // Test the provided signatures against the actor and "attributedTo"
394 if (!empty($attributed_to) && !empty($actor)) {
395 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
397 $trust_source = in_array($actor, $signer);
401 // $trust_source is called by reference and is set to true if the content was retrieved successfully
402 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
403 if (empty($object_data)) {
404 Logger::info('No object data found', ['activity' => $activity]);
408 if (!$trust_source) {
409 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
413 if (!empty($body) && empty($object_data['raw'])) {
414 $object_data['raw'] = $body;
417 // Internal flag for thread completion. See Processor.php
418 if (!empty($activity['thread-completion'])) {
419 $object_data['thread-completion'] = $activity['thread-completion'];
424 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
425 $item = ActivityPub\Processor::createItem($object_data);
426 ActivityPub\Processor::postItem($object_data, $item);
431 if ($object_data['object_type'] == 'as:tag') {
432 ActivityPub\Processor::addTag($object_data);
437 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
438 $object_data['thread-completion'] = true;
440 $item = ActivityPub\Processor::createItem($object_data);
441 ActivityPub\Processor::postItem($object_data, $item);
443 $announce_object_data = self::processObject($activity);
444 $announce_object_data['name'] = $type;
445 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
446 $announce_object_data['object_id'] = $object_data['object_id'];
447 $announce_object_data['object_type'] = $object_data['object_type'];
448 $announce_object_data['push'] = $push;
451 $announce_object_data['raw'] = $body;
454 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
459 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
460 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
465 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
466 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
470 case 'as:TentativeAccept':
471 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
472 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
477 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
478 ActivityPub\Processor::updateItem($object_data);
479 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
480 ActivityPub\Processor::updatePerson($object_data);
485 if ($object_data['object_type'] == 'as:Tombstone') {
486 ActivityPub\Processor::deleteItem($object_data);
487 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
488 ActivityPub\Processor::deletePerson($object_data);
493 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
494 ActivityPub\Processor::followUser($object_data);
495 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
496 $object_data['reply-to-id'] = $object_data['object_id'];
497 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
502 if ($object_data['object_type'] == 'as:Follow') {
503 ActivityPub\Processor::acceptFollowUser($object_data);
504 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
505 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
510 if ($object_data['object_type'] == 'as:Follow') {
511 ActivityPub\Processor::rejectFollowUser($object_data);
512 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
513 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
518 if (($object_data['object_type'] == 'as:Follow') &&
519 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
520 ActivityPub\Processor::undoFollowUser($object_data);
521 } elseif (($object_data['object_type'] == 'as:Accept') &&
522 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
523 ActivityPub\Processor::rejectFollowUser($object_data);
524 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
525 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
526 ActivityPub\Processor::undoActivity($object_data);
531 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
537 * Fetch the receiver list from an activity array
539 * @param array $activity
540 * @param string $actor
542 * @param boolean $fetch_unlisted
544 * @return array with receivers (user id)
547 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
549 $reply = $receivers = [];
551 // When it is an answer, we inherite the receivers from the parent
552 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
553 if (!empty($replyto)) {
556 // Fix possibly wrong item URI (could be an answer to a plink uri)
557 $fixedReplyTo = Item::getURIByLink($replyto);
558 if (!empty($fixedReplyTo)) {
559 $reply[] = $fixedReplyTo;
563 // Fetch all posts that refer to the object id
564 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
565 if (!empty($object_id)) {
566 $reply[] = $object_id;
569 if (!empty($reply)) {
570 $parents = Item::select(['uid'], ['uri' => $reply]);
571 while ($parent = Item::fetch($parents)) {
572 $receivers['uid:' . $parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
576 if (!empty($actor)) {
577 $profile = APContact::getByURL($actor);
578 $followers = $profile['followers'] ?? '';
580 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
582 Logger::info('Empty actor', ['activity' => $activity]);
586 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
587 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
588 if (empty($receiver_list)) {
592 foreach ($receiver_list as $receiver) {
593 if ($receiver == self::PUBLIC_COLLECTION) {
594 $receivers['uid:0'] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
597 // Add receiver "-1" for unlisted posts
598 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
599 $receivers['uid:-1'] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
602 // Fetch the receivers for the public and the followers collection
603 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
604 $receivers = self::getReceiverForActor($actor, $tags, $receivers);
608 // Fetching all directly addressed receivers
609 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
610 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
611 if (!DBA::isResult($contact)) {
615 // Check if the potential receiver is following the actor
616 // Exception: The receiver is targetted via "to" or this is a comment
617 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
618 $networks = Protocol::FEDERATED;
619 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
620 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
622 // Forum posts are only accepted from forum contacts
623 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
624 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
627 if (!DBA::exists('contact', $condition)) {
632 $type = $receivers['uid:' . $contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
633 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
636 $type = self::TARGET_TO;
639 $type = self::TARGET_CC;
642 $type = self::TARGET_BTO;
645 $type = self::TARGET_BCC;
649 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
654 self::switchContacts($receivers, $actor);
660 * Fetch the receiver list of a given actor
662 * @param string $actor
665 * @return array with receivers (user id)
668 private static function getReceiverForActor($actor, $tags, $receivers)
670 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
671 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
673 $condition = DBA::mergeConditions($basecondition, ['nurl' => Strings::normaliseLink($actor)]);
674 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
675 while ($contact = DBA::fetch($contacts)) {
676 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
677 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
680 DBA::close($contacts);
682 // The queries are split because of performance issues
683 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?)", Strings::normaliseLink($actor), $actor]);
684 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
685 while ($contact = DBA::fetch($contacts)) {
686 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
687 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
690 DBA::close($contacts);
695 * Tests if the contact is a valid receiver for this actor
697 * @param array $contact
698 * @param string $actor
701 * @return bool with receivers (user id)
704 private static function isValidReceiverForActor($contact, $actor, $tags)
706 // Public contacts are no valid receiver
707 if ($contact['uid'] == 0) {
711 // Are we following the contact? Then this is a valid receiver
712 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
716 // When the possible receiver isn't a community, then it is no valid receiver
717 $owner = User::getOwnerDataById($contact['uid']);
718 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
722 // Is the community account tagged?
723 foreach ($tags as $tag) {
724 if ($tag['type'] != 'Mention') {
728 if ($tag['href'] == $owner['url']) {
737 * Switches existing contacts to ActivityPub
739 * @param integer $cid Contact ID
740 * @param integer $uid User ID
741 * @param string $url Profile URL
742 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
743 * @throws \ImagickException
745 public static function switchContact($cid, $uid, $url)
747 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
748 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
752 if (Contact::updateFromProbe($cid)) {
753 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
756 // Send a new follow request to be sure that the connection still exists
757 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
758 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
759 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
769 * @throws \ImagickException
771 private static function switchContacts($receivers, $actor)
777 foreach ($receivers as $receiver) {
778 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
779 if (DBA::isResult($contact)) {
780 self::switchContact($contact['id'], $receiver['uid'], $actor);
783 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
784 if (DBA::isResult($contact)) {
785 self::switchContact($contact['id'], $receiver['uid'], $actor);
793 * @param $object_data
794 * @param array $activity
798 private static function addActivityFields($object_data, $activity)
800 if (!empty($activity['published']) && empty($object_data['published'])) {
801 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
804 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
805 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
808 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
809 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
811 if (!empty($object_data['object_id'])) {
812 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
813 $objectId = Item::getURIByLink($object_data['object_id']);
814 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
815 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
816 $object_data['object_id'] = $objectId;
824 * Fetches the object data from external ressources if needed
826 * @param string $object_id Object ID of the the provided object
827 * @param array $object The provided object array
828 * @param boolean $trust_source Do we trust the provided object?
829 * @param integer $uid User ID for the signature that we use to fetch data
831 * @return array|false with trusted and valid object data
832 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
833 * @throws \ImagickException
835 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
837 // By fetching the type we check if the object is complete.
838 $type = JsonLD::fetchElement($object, '@type');
840 if (!$trust_source || empty($type)) {
841 $data = ActivityPub::fetchContent($object_id, $uid);
843 $object = JsonLD::compact($data);
844 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
846 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
848 $item = Item::selectFirst([], ['uri' => $object_id]);
849 if (!DBA::isResult($item)) {
850 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
853 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
854 $data = ActivityPub\Transmitter::createNote($item);
855 $object = JsonLD::compact($data);
858 $id = JsonLD::fetchElement($object, '@id');
860 Logger::info('Empty id');
864 if ($id != $object_id) {
865 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
869 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
872 $type = JsonLD::fetchElement($object, '@type');
874 Logger::info('Empty type');
878 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
879 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
880 $object_data = self::processObject($object);
883 $object_data['raw'] = json_encode($data);
888 if ($type == 'as:Announce') {
889 $object_id = JsonLD::fetchElement($object, 'object', '@id');
890 if (empty($object_id) || !is_string($object_id)) {
893 return self::fetchObject($object_id, [], false, $uid);
896 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
901 * Convert tags from JSON-LD format into a simplified format
903 * @param array $tags Tags in JSON-LD format
905 * @return array with tags in a simplified format
907 private static function processTags(array $tags)
911 foreach ($tags as $tag) {
916 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
917 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
918 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
920 if (empty($element['type'])) {
924 if (empty($element['href'])) {
925 $element['href'] = $element['name'];
928 $taglist[] = $element;
934 * Convert emojis from JSON-LD format into a simplified format
936 * @param array $emojis
937 * @return array with emojis in a simplified format
939 private static function processEmojis(array $emojis)
943 foreach ($emojis as $emoji) {
944 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
948 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
949 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
952 $emojilist[] = $element;
959 * Convert attachments from JSON-LD format into a simplified format
961 * @param array $attachments Attachments in JSON-LD format
963 * @return array Attachments in a simplified format
965 private static function processAttachments(array $attachments)
969 // Removes empty values
970 $attachments = array_filter($attachments);
972 foreach ($attachments as $attachment) {
973 switch (JsonLD::fetchElement($attachment, '@type')) {
978 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
979 foreach ($urls as $url) {
980 // Single scalar URL case
981 if (is_string($url)) {
986 $href = JsonLD::fetchElement($url, 'as:href', '@id');
987 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
988 if (Strings::startsWith($mediaType, 'image')) {
997 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
998 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1000 'image' => $pageImage,
1005 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1006 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1007 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1008 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1012 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1013 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1014 $imagePreviewUrl = null;
1016 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1017 $imageVariants = [];
1018 $previewVariants = [];
1019 foreach ($urls as $url) {
1020 // Scalar URL, no discrimination possible
1021 if (is_string($url)) {
1022 $imageFullUrl = $url;
1026 // Not sure what to do with a different Link media type than the base Image, we skip
1027 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1031 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1033 // Default URL choice if no discriminating width is provided
1034 $imageFullUrl = $href ?? $imageFullUrl;
1036 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1038 if ($href && $width) {
1039 $imageVariants[$width] = $href;
1040 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1041 $previewVariants[abs(632 - $width)] = $href;
1045 if ($imageVariants) {
1046 // Taking the maximum size image
1047 ksort($imageVariants);
1048 $imageFullUrl = array_pop($imageVariants);
1050 // Taking the minimum number distance to the target distance
1051 ksort($previewVariants);
1052 $imagePreviewUrl = array_shift($previewVariants);
1055 unset($imageVariants);
1056 unset($previewVariants);
1060 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1061 'mediaType' => $mediaType,
1062 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1063 'url' => $imageFullUrl,
1064 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1069 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1070 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1071 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1072 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1081 * Fetch the original source or content with the "language" Markdown or HTML
1083 * @param array $object
1084 * @param array $object_data
1087 * @throws \Exception
1089 private static function getSource($object, $object_data)
1091 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1092 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1093 if (!empty($object_data['source'])) {
1094 return $object_data;
1097 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1098 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1099 if (!empty($object_data['source'])) {
1100 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1101 return $object_data;
1104 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1105 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1106 if (!empty($object_data['source'])) {
1107 $object_data['source'] = HTML::toBBCode($object_data['source']);
1108 return $object_data;
1111 return $object_data;
1115 * Check if the "as:url" element is an array with multiple links
1116 * This is the case with audio and video posts.
1117 * Then the links are added as attachments
1119 * @param array $object The raw object
1120 * @param array $object_data The parsed object data for later processing
1121 * @return array the object data
1123 private static function processAttachmentUrls(array $object, array $object_data) {
1124 // Check if this is some url with multiple links
1125 if (empty($object['as:url'])) {
1126 return $object_data;
1129 $urls = $object['as:url'];
1130 $keys = array_keys($urls);
1131 if (!is_numeric(array_pop($keys))) {
1132 return $object_data;
1137 foreach ($urls as $url) {
1138 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1142 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1147 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1148 if (empty($mediatype)) {
1152 if ($mediatype == 'text/html') {
1153 $object_data['alternate-url'] = $href;
1156 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1158 if ($filetype == 'audio') {
1159 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1160 } elseif ($filetype == 'video') {
1161 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1163 // We save bandwidth by using a moderate height
1164 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1165 if (!empty($attachments[$filetype]['height']) &&
1166 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1170 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1174 foreach ($attachments as $type => $attachment) {
1175 $object_data['attachments'][] = ['type' => $type,
1176 'mediaType' => $attachment['type'],
1178 'url' => $attachment['url']];
1180 return $object_data;
1184 * Fetches data from the object part of an activity
1186 * @param array $object
1189 * @throws \Exception
1191 private static function processObject($object)
1193 if (!JsonLD::fetchElement($object, '@id')) {
1198 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1199 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1200 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1202 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1203 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1204 $object_data['reply-to-id'] = $object_data['id'];
1206 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1207 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1208 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1209 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1210 $object_data['reply-to-id'] = $replyToId;
1214 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1215 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1217 if (empty($object_data['updated'])) {
1218 $object_data['updated'] = $object_data['published'];
1221 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1222 $object_data['published'] = $object_data['updated'];
1225 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1226 if (empty($actor)) {
1227 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1230 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1231 $location = JsonLD::fetchElement($location, 'location', '@value');
1233 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1234 // down to HTML and then finally format to plaintext.
1235 $location = Markdown::convert($location);
1236 $location = BBCode::convert($location);
1237 $location = HTML::toPlaintext($location);
1240 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1241 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1242 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1243 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1244 $object_data['actor'] = $object_data['author'] = $actor;
1245 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1246 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1247 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1248 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1249 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1250 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1251 $object_data = self::getSource($object, $object_data);
1252 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1253 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1254 $object_data['location'] = $location;
1255 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1256 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1257 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1258 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1259 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1260 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1261 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1262 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1263 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1264 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1266 // Special treatment for Hubzilla links
1267 if (is_array($object_data['alternate-url'])) {
1268 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1270 if (!is_string($object_data['alternate-url'])) {
1271 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1275 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1276 $object_data = self::processAttachmentUrls($object, $object_data);
1279 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1280 $receivers = $reception_types = [];
1281 foreach ($receiverdata as $key => $data) {
1282 $receivers[$key] = $data['uid'];
1283 $reception_types[$data['uid']] = $data['type'] ?? 0;
1286 $object_data['receiver'] = $receivers;
1287 $object_data['reception_type'] = $reception_types;
1289 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1290 unset($object_data['receiver']['uid:-1']);
1292 // Common object data:
1295 // @context, type, actor, signature, mediaType, duration, replies, icon
1297 // Also missing: (Defined in the standard, but currently unused)
1298 // audience, preview, endTime, startTime, image
1303 // contentMap, announcement_count, announcements, context_id, likes, like_count
1304 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1309 // category, licence, language, commentsEnabled
1312 // views, waitTranscoding, state, support, subtitleLanguage
1313 // likes, dislikes, shares, comments
1315 return $object_data;