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;
69 * Checks if the web request is done for the AP protocol
71 * @return bool is it AP?
73 public static function isRequest()
75 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
76 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
80 * Checks incoming message from the inbox
84 * @param integer $uid User ID
87 public static function processInbox($body, $header, $uid)
89 $http_signer = HTTPSignature::getSigner($body, $header);
90 if (empty($http_signer)) {
91 Logger::warning('Invalid HTTP signature, message will be discarded.');
94 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
97 $signer = [$http_signer];
98 $activity = json_decode($body, true);
100 if (empty($activity)) {
101 Logger::warning('Invalid body.');
105 $ldactivity = JsonLD::compact($activity);
107 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
109 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
111 if (LDSignature::isSigned($activity)) {
112 $ld_signer = LDSignature::getSigner($activity);
113 if (empty($ld_signer)) {
114 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
115 } elseif ($ld_signer != $http_signer) {
116 $signer[] = $ld_signer;
118 if (!empty($ld_signer && ($actor == $http_signer))) {
119 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
120 $trust_source = true;
121 } elseif (!empty($ld_signer)) {
122 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
123 $trust_source = true;
124 } elseif ($actor == $http_signer) {
125 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
126 $trust_source = true;
128 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
129 $trust_source = false;
131 } elseif ($actor == $http_signer) {
132 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
133 $trust_source = true;
135 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
136 $trust_source = false;
139 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
143 * Fetches the object type for a given object id
145 * @param array $activity
146 * @param string $object_id Object ID of the the provided object
147 * @param integer $uid User ID
149 * @return string with object type
150 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
151 * @throws \ImagickException
153 private static function fetchObjectType($activity, $object_id, $uid = 0)
155 if (!empty($activity['as:object'])) {
156 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
157 if (!empty($object_type)) {
162 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
163 // We just assume "note" since it doesn't make a difference for the further processing
167 $profile = APContact::getByURL($object_id);
168 if (!empty($profile['type'])) {
169 return 'as:' . $profile['type'];
172 $data = ActivityPub::fetchContent($object_id, $uid);
174 $object = JsonLD::compact($data);
175 $type = JsonLD::fetchElement($object, '@type');
185 * Prepare the object array
187 * @param array $activity Array with activity data
188 * @param integer $uid User ID
189 * @param boolean $push Message had been pushed to our system
190 * @param boolean $trust_source Do we trust the source?
192 * @return array with object data
193 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
194 * @throws \ImagickException
196 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
198 $id = JsonLD::fetchElement($activity, '@id');
199 if (!empty($id) && !$trust_source) {
200 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
201 if (!empty($fetched_activity)) {
202 $object = JsonLD::compact($fetched_activity);
203 $fetched_id = JsonLD::fetchElement($object, '@id');
204 if ($fetched_id == $id) {
205 Logger::info('Activity had been fetched successfully', ['id' => $id]);
206 $trust_source = true;
209 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
212 Logger::info('Activity could not been fetched', ['id' => $id]);
216 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
218 Logger::info('Empty actor', ['activity' => $activity]);
222 $type = JsonLD::fetchElement($activity, '@type');
224 // Fetch all receivers from to, cc, bto and bcc
225 $receiverdata = self::getReceivers($activity, $actor);
226 $receivers = $reception_types = [];
227 foreach ($receiverdata as $key => $data) {
228 $receivers[$key] = $data['uid'];
229 $reception_types[$data['uid']] = $data['type'] ?? 0;
232 // When it is a delivery to a personal inbox we add that user to the receivers
234 $additional = ['uid:' . $uid => $uid];
235 $receivers = array_merge($receivers, $additional);
236 if (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER])) {
237 $reception_types[$uid] = self::TARGET_BCC;
240 // We possibly need some user to fetch private content,
241 // so we fetch the first out ot the list.
242 $uid = self::getFirstUserFromReceivers($receivers);
245 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
246 if (empty($object_id)) {
247 Logger::log('No object found', Logger::DEBUG);
251 if (!is_string($object_id)) {
252 Logger::info('Invalid object id', ['object' => $object_id]);
256 $object_type = self::fetchObjectType($activity, $object_id, $uid);
258 // Fetch the content only on activities where this matters
259 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
260 // Always fetch on "Announce"
261 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
262 if (empty($object_data)) {
263 Logger::log("Object data couldn't be processed", Logger::DEBUG);
267 $object_data['object_id'] = $object_id;
269 if ($type == 'as:Announce') {
270 $object_data['push'] = false;
272 $object_data['push'] = $push;
275 // Test if it is an answer to a mail
276 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
277 $object_data['directmessage'] = true;
279 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
281 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
282 // Create a mostly empty array out of the activity data (instead of the object).
283 // This way we later don't have to check for the existence of ech individual array element.
284 $object_data = self::processObject($activity);
285 $object_data['name'] = $type;
286 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
287 $object_data['object_id'] = $object_id;
288 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
289 } elseif (in_array($type, ['as:Add'])) {
291 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
292 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
293 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
294 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
295 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
298 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
299 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
300 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
301 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
302 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
304 // An Undo is done on the object of an object, so we need that type as well
305 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
306 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
310 $object_data = self::addActivityFields($object_data, $activity);
312 if (empty($object_data['object_type'])) {
313 $object_data['object_type'] = $object_type;
316 $object_data['type'] = $type;
317 $object_data['actor'] = $actor;
318 $object_data['item_receiver'] = $receivers;
319 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
320 $object_data['reception_type'] = $reception_types;
322 $author = $object_data['author'] ?? $actor;
323 if (!empty($author) && !empty($object_data['id'])) {
324 $author_host = parse_url($author, PHP_URL_HOST);
325 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
326 if ($author_host == $id_host) {
327 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
329 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
330 $trust_source = false;
334 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
340 * Fetches the first user id from the receiver array
342 * @param array $receivers Array with receivers
343 * @return integer user id;
345 public static function getFirstUserFromReceivers($receivers)
347 foreach ($receivers as $receiver) {
348 if (!empty($receiver)) {
356 * Processes the activity object
358 * @param array $activity Array with activity data
359 * @param string $body
360 * @param integer $uid User ID
361 * @param boolean $trust_source Do we trust the source?
362 * @param boolean $push Message had been pushed to our system
365 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
367 $type = JsonLD::fetchElement($activity, '@type');
369 Logger::info('Empty type', ['activity' => $activity]);
373 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
374 Logger::info('Empty object', ['activity' => $activity]);
378 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
380 Logger::info('Empty actor', ['activity' => $activity]);
384 if (is_array($activity['as:object'])) {
385 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
390 // Test the provided signatures against the actor and "attributedTo"
392 if (!empty($attributed_to) && !empty($actor)) {
393 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
395 $trust_source = in_array($actor, $signer);
399 // $trust_source is called by reference and is set to true if the content was retrieved successfully
400 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
401 if (empty($object_data)) {
402 Logger::info('No object data found', ['activity' => $activity]);
406 if (!$trust_source) {
407 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
411 if (!empty($body) && empty($object_data['raw'])) {
412 $object_data['raw'] = $body;
415 // Internal flag for thread completion. See Processor.php
416 if (!empty($activity['thread-completion'])) {
417 $object_data['thread-completion'] = $activity['thread-completion'];
422 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
423 $item = ActivityPub\Processor::createItem($object_data);
424 ActivityPub\Processor::postItem($object_data, $item);
429 if ($object_data['object_type'] == 'as:tag') {
430 ActivityPub\Processor::addTag($object_data);
435 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
436 $object_data['thread-completion'] = true;
438 $item = ActivityPub\Processor::createItem($object_data);
439 ActivityPub\Processor::postItem($object_data, $item);
441 $announce_object_data = self::processObject($activity);
442 $announce_object_data['name'] = $type;
443 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
444 $announce_object_data['object_id'] = $object_data['object_id'];
445 $announce_object_data['object_type'] = $object_data['object_type'];
446 $announce_object_data['push'] = $push;
449 $announce_object_data['raw'] = $body;
452 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
457 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
458 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
463 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
464 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
468 case 'as:TentativeAccept':
469 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
470 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
475 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
476 ActivityPub\Processor::updateItem($object_data);
477 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
478 ActivityPub\Processor::updatePerson($object_data);
483 if ($object_data['object_type'] == 'as:Tombstone') {
484 ActivityPub\Processor::deleteItem($object_data);
485 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
486 ActivityPub\Processor::deletePerson($object_data);
491 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
492 ActivityPub\Processor::followUser($object_data);
493 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
494 $object_data['reply-to-id'] = $object_data['object_id'];
495 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
500 if ($object_data['object_type'] == 'as:Follow') {
501 ActivityPub\Processor::acceptFollowUser($object_data);
502 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
503 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
508 if ($object_data['object_type'] == 'as:Follow') {
509 ActivityPub\Processor::rejectFollowUser($object_data);
510 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
511 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
516 if (($object_data['object_type'] == 'as:Follow') &&
517 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
518 ActivityPub\Processor::undoFollowUser($object_data);
519 } elseif (($object_data['object_type'] == 'as:Accept') &&
520 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
521 ActivityPub\Processor::rejectFollowUser($object_data);
522 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
523 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
524 ActivityPub\Processor::undoActivity($object_data);
529 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
535 * Fetch the receiver list from an activity array
537 * @param array $activity
538 * @param string $actor
540 * @param boolean $fetch_unlisted
542 * @return array with receivers (user id)
545 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
549 // When it is an answer, we inherite the receivers from the parent
550 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
551 if (!empty($replyto)) {
552 // Fix possibly wrong item URI (could be an answer to a plink uri)
553 $fixedReplyTo = Item::getURIByLink($replyto);
554 $replyto = $fixedReplyTo ?: $replyto;
556 $parents = Item::select(['uid'], ['uri' => $replyto]);
557 while ($parent = Item::fetch($parents)) {
558 $receivers['uid:' . $parent['uid']] = ['uid' => $parent['uid']];
562 if (!empty($actor)) {
563 $profile = APContact::getByURL($actor);
564 $followers = $profile['followers'] ?? '';
566 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
568 Logger::info('Empty actor', ['activity' => $activity]);
572 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
573 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
574 if (empty($receiver_list)) {
578 foreach ($receiver_list as $receiver) {
579 if ($receiver == self::PUBLIC_COLLECTION) {
580 $receivers['uid:0'] = ['uid' => 0, 'type' => self::TARGET_UNKNOWN];
583 // Add receiver "-1" for unlisted posts
584 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
585 $receivers['uid:-1'] = ['uid' => -1, 'type' => self::TARGET_UNKNOWN];
588 // Fetch the receivers for the public and the followers collection
589 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
590 $receivers = self::getReceiverForActor($actor, $tags, $receivers);
594 // Fetching all directly addressed receivers
595 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
596 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
597 if (!DBA::isResult($contact)) {
601 // Check if the potential receiver is following the actor
602 // Exception: The receiver is targetted via "to" or this is a comment
603 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
604 $networks = Protocol::FEDERATED;
605 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
606 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
608 // Forum posts are only accepted from forum contacts
609 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
610 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
613 if (!DBA::exists('contact', $condition)) {
618 $type = $receivers['uid:' . $contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
619 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER])) {
622 $type = self::TARGET_TO;
625 $type = self::TARGET_CC;
628 $type = self::TARGET_BTO;
631 $type = self::TARGET_BCC;
635 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
640 self::switchContacts($receivers, $actor);
646 * Fetch the receiver list of a given actor
648 * @param string $actor
651 * @return array with receivers (user id)
654 private static function getReceiverForActor($actor, $tags, $receivers)
656 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
657 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
659 $condition = DBA::mergeConditions($basecondition, ['nurl' => Strings::normaliseLink($actor)]);
660 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
661 while ($contact = DBA::fetch($contacts)) {
662 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
663 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
666 DBA::close($contacts);
668 // The queries are split because of performance issues
669 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?)", Strings::normaliseLink($actor), $actor]);
670 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
671 while ($contact = DBA::fetch($contacts)) {
672 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
673 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
676 DBA::close($contacts);
681 * Tests if the contact is a valid receiver for this actor
683 * @param array $contact
684 * @param string $actor
687 * @return bool with receivers (user id)
690 private static function isValidReceiverForActor($contact, $actor, $tags)
692 // Public contacts are no valid receiver
693 if ($contact['uid'] == 0) {
697 // Are we following the contact? Then this is a valid receiver
698 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
702 // When the possible receiver isn't a community, then it is no valid receiver
703 $owner = User::getOwnerDataById($contact['uid']);
704 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
708 // Is the community account tagged?
709 foreach ($tags as $tag) {
710 if ($tag['type'] != 'Mention') {
714 if ($tag['href'] == $owner['url']) {
723 * Switches existing contacts to ActivityPub
725 * @param integer $cid Contact ID
726 * @param integer $uid User ID
727 * @param string $url Profile URL
728 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
729 * @throws \ImagickException
731 public static function switchContact($cid, $uid, $url)
733 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
734 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
738 if (Contact::updateFromProbe($cid)) {
739 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
742 // Send a new follow request to be sure that the connection still exists
743 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
744 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
745 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
755 * @throws \ImagickException
757 private static function switchContacts($receivers, $actor)
763 foreach ($receivers as $receiver) {
764 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
765 if (DBA::isResult($contact)) {
766 self::switchContact($contact['id'], $receiver['uid'], $actor);
769 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
770 if (DBA::isResult($contact)) {
771 self::switchContact($contact['id'], $receiver['uid'], $actor);
779 * @param $object_data
780 * @param array $activity
784 private static function addActivityFields($object_data, $activity)
786 if (!empty($activity['published']) && empty($object_data['published'])) {
787 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
790 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
791 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
794 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
795 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
797 if (!empty($object_data['object_id'])) {
798 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
799 $objectId = Item::getURIByLink($object_data['object_id']);
800 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
801 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
802 $object_data['object_id'] = $objectId;
810 * Fetches the object data from external ressources if needed
812 * @param string $object_id Object ID of the the provided object
813 * @param array $object The provided object array
814 * @param boolean $trust_source Do we trust the provided object?
815 * @param integer $uid User ID for the signature that we use to fetch data
817 * @return array|false with trusted and valid object data
818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
819 * @throws \ImagickException
821 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
823 // By fetching the type we check if the object is complete.
824 $type = JsonLD::fetchElement($object, '@type');
826 if (!$trust_source || empty($type)) {
827 $data = ActivityPub::fetchContent($object_id, $uid);
829 $object = JsonLD::compact($data);
830 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
832 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
834 $item = Item::selectFirst([], ['uri' => $object_id]);
835 if (!DBA::isResult($item)) {
836 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
839 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
840 $data = ActivityPub\Transmitter::createNote($item);
841 $object = JsonLD::compact($data);
844 $id = JsonLD::fetchElement($object, '@id');
846 Logger::info('Empty id');
850 if ($id != $object_id) {
851 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
855 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
858 $type = JsonLD::fetchElement($object, '@type');
860 Logger::info('Empty type');
864 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
865 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
866 $object_data = self::processObject($object);
869 $object_data['raw'] = json_encode($data);
874 if ($type == 'as:Announce') {
875 $object_id = JsonLD::fetchElement($object, 'object', '@id');
876 if (empty($object_id) || !is_string($object_id)) {
879 return self::fetchObject($object_id, [], false, $uid);
882 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
887 * Convert tags from JSON-LD format into a simplified format
889 * @param array $tags Tags in JSON-LD format
891 * @return array with tags in a simplified format
893 private static function processTags(array $tags)
897 foreach ($tags as $tag) {
902 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
903 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
904 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
906 if (empty($element['type'])) {
910 if (empty($element['href'])) {
911 $element['href'] = $element['name'];
914 $taglist[] = $element;
920 * Convert emojis from JSON-LD format into a simplified format
922 * @param array $emojis
923 * @return array with emojis in a simplified format
925 private static function processEmojis(array $emojis)
929 foreach ($emojis as $emoji) {
930 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
934 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
935 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
938 $emojilist[] = $element;
945 * Convert attachments from JSON-LD format into a simplified format
947 * @param array $attachments Attachments in JSON-LD format
949 * @return array Attachments in a simplified format
951 private static function processAttachments(array $attachments)
955 // Removes empty values
956 $attachments = array_filter($attachments);
958 foreach ($attachments as $attachment) {
959 switch (JsonLD::fetchElement($attachment, '@type')) {
964 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
965 foreach ($urls as $url) {
966 // Single scalar URL case
967 if (is_string($url)) {
972 $href = JsonLD::fetchElement($url, 'as:href', '@id');
973 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
974 if (Strings::startsWith($mediaType, 'image')) {
983 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
984 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
986 'image' => $pageImage,
991 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
992 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
993 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
994 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
998 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
999 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1000 $imagePreviewUrl = null;
1002 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1003 $imageVariants = [];
1004 $previewVariants = [];
1005 foreach ($urls as $url) {
1006 // Scalar URL, no discrimination possible
1007 if (is_string($url)) {
1008 $imageFullUrl = $url;
1012 // Not sure what to do with a different Link media type than the base Image, we skip
1013 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1017 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1019 // Default URL choice if no discriminating width is provided
1020 $imageFullUrl = $href ?? $imageFullUrl;
1022 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1024 if ($href && $width) {
1025 $imageVariants[$width] = $href;
1026 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1027 $previewVariants[abs(632 - $width)] = $href;
1031 if ($imageVariants) {
1032 // Taking the maximum size image
1033 ksort($imageVariants);
1034 $imageFullUrl = array_pop($imageVariants);
1036 // Taking the minimum number distance to the target distance
1037 ksort($previewVariants);
1038 $imagePreviewUrl = array_shift($previewVariants);
1041 unset($imageVariants);
1042 unset($previewVariants);
1046 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1047 'mediaType' => $mediaType,
1048 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1049 'url' => $imageFullUrl,
1050 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
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:url', '@id')
1067 * Fetch the original source or content with the "language" Markdown or HTML
1069 * @param array $object
1070 * @param array $object_data
1073 * @throws \Exception
1075 private static function getSource($object, $object_data)
1077 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1078 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1079 if (!empty($object_data['source'])) {
1080 return $object_data;
1083 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1084 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1085 if (!empty($object_data['source'])) {
1086 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1087 return $object_data;
1090 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1091 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1092 if (!empty($object_data['source'])) {
1093 $object_data['source'] = HTML::toBBCode($object_data['source']);
1094 return $object_data;
1097 return $object_data;
1101 * Check if the "as:url" element is an array with multiple links
1102 * This is the case with audio and video posts.
1103 * Then the links are added as attachments
1105 * @param array $object The raw object
1106 * @param array $object_data The parsed object data for later processing
1107 * @return array the object data
1109 private static function processAttachmentUrls(array $object, array $object_data) {
1110 // Check if this is some url with multiple links
1111 if (empty($object['as:url'])) {
1112 return $object_data;
1115 $urls = $object['as:url'];
1116 $keys = array_keys($urls);
1117 if (!is_numeric(array_pop($keys))) {
1118 return $object_data;
1123 foreach ($urls as $url) {
1124 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1128 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1133 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1134 if (empty($mediatype)) {
1138 if ($mediatype == 'text/html') {
1139 $object_data['alternate-url'] = $href;
1142 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1144 if ($filetype == 'audio') {
1145 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1146 } elseif ($filetype == 'video') {
1147 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1149 // We save bandwidth by using a moderate height
1150 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1151 if (!empty($attachments[$filetype]['height']) &&
1152 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1156 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1160 foreach ($attachments as $type => $attachment) {
1161 $object_data['attachments'][] = ['type' => $type,
1162 'mediaType' => $attachment['type'],
1164 'url' => $attachment['url']];
1166 return $object_data;
1170 * Fetches data from the object part of an activity
1172 * @param array $object
1175 * @throws \Exception
1177 private static function processObject($object)
1179 if (!JsonLD::fetchElement($object, '@id')) {
1184 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1185 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1186 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1188 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1189 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1190 $object_data['reply-to-id'] = $object_data['id'];
1192 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1193 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1194 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1195 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1196 $object_data['reply-to-id'] = $replyToId;
1200 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1201 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1203 if (empty($object_data['updated'])) {
1204 $object_data['updated'] = $object_data['published'];
1207 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1208 $object_data['published'] = $object_data['updated'];
1211 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1212 if (empty($actor)) {
1213 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1216 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1217 $location = JsonLD::fetchElement($location, 'location', '@value');
1219 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1220 // down to HTML and then finally format to plaintext.
1221 $location = Markdown::convert($location);
1222 $location = BBCode::convert($location);
1223 $location = HTML::toPlaintext($location);
1226 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1227 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1228 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1229 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1230 $object_data['actor'] = $object_data['author'] = $actor;
1231 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1232 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1233 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1234 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1235 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1236 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1237 $object_data = self::getSource($object, $object_data);
1238 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1239 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1240 $object_data['location'] = $location;
1241 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1242 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1243 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1244 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1245 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1246 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1247 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1248 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1249 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1250 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1252 // Special treatment for Hubzilla links
1253 if (is_array($object_data['alternate-url'])) {
1254 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1256 if (!is_string($object_data['alternate-url'])) {
1257 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1261 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1262 $object_data = self::processAttachmentUrls($object, $object_data);
1265 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1267 foreach ($receiverdata as $key => $data) {
1268 $receivers[$key] = $data['uid'];
1271 $object_data['receiver'] = $receivers;
1273 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1274 unset($object_data['receiver']['uid:-1']);
1276 // Common object data:
1279 // @context, type, actor, signature, mediaType, duration, replies, icon
1281 // Also missing: (Defined in the standard, but currently unused)
1282 // audience, preview, endTime, startTime, image
1287 // contentMap, announcement_count, announcements, context_id, likes, like_count
1288 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1293 // category, licence, language, commentsEnabled
1296 // views, waitTranscoding, state, support, subtitleLanguage
1297 // likes, dislikes, shares, comments
1299 return $object_data;