3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\Post;
34 use Friendica\Model\User;
35 use Friendica\Protocol\Activity;
36 use Friendica\Protocol\ActivityPub;
37 use Friendica\Util\HTTPSignature;
38 use Friendica\Util\JsonLD;
39 use Friendica\Util\LDSignature;
40 use Friendica\Util\Strings;
43 * ActivityPub Receiver Protocol class
48 * Check what this is meant to do:
57 const PUBLIC_COLLECTION = 'as:Public';
58 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
59 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio'];
60 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
62 const TARGET_UNKNOWN = 0;
67 const TARGET_FOLLOWER = 5;
68 const TARGET_ANSWER = 6;
69 const TARGET_GLOBAL = 7;
72 * Checks if the web request is done for the AP protocol
74 * @return bool is it AP?
76 public static function isRequest()
78 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
79 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
83 * Checks incoming message from the inbox
87 * @param integer $uid User ID
90 public static function processInbox($body, $header, $uid)
92 $activity = json_decode($body, true);
93 if (empty($activity)) {
94 Logger::warning('Invalid body.');
98 $ldactivity = JsonLD::compact($activity);
100 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
102 $apcontact = APContact::getByURL($actor);
103 if (empty($apcontact)) {
104 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
106 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
107 self::processRelayPost($ldactivity, $actor);
110 APContact::unmarkForArchival($apcontact);
113 $http_signer = HTTPSignature::getSigner($body, $header);
114 if ($http_signer === false) {
115 Logger::warning('Invalid HTTP signature, message will be discarded.');
117 } elseif (empty($http_signer)) {
118 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
121 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
124 $signer = [$http_signer];
126 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
128 if (LDSignature::isSigned($activity)) {
129 $ld_signer = LDSignature::getSigner($activity);
130 if (empty($ld_signer)) {
131 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
132 } elseif ($ld_signer != $http_signer) {
133 $signer[] = $ld_signer;
135 if (!empty($ld_signer && ($actor == $http_signer))) {
136 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
137 $trust_source = true;
138 } elseif (!empty($ld_signer)) {
139 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
140 $trust_source = true;
141 } elseif ($actor == $http_signer) {
142 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
143 $trust_source = true;
145 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
146 $trust_source = false;
148 } elseif ($actor == $http_signer) {
149 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
150 $trust_source = true;
152 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
153 $trust_source = false;
156 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
160 * Process incoming posts from relays
162 * @param array $activity
163 * @param string $actor
166 private static function processRelayPost(array $activity, string $actor)
168 $type = JsonLD::fetchElement($activity, '@type');
170 Logger::info('Empty type', ['activity' => $activity]);
174 if ($type != 'as:Announce') {
175 Logger::info('Not an announcement', ['activity' => $activity]);
179 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
180 if (empty($object_id)) {
181 Logger::info('No object id found', ['activity' => $activity]);
185 $contact = Contact::getByURL($actor);
186 if (empty($contact)) {
187 Logger::info('Relay contact not found', ['actor' => $actor]);
191 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
192 Logger::notice('Relay is no sharer', ['actor' => $actor]);
196 Logger::info('Got relayed message id', ['id' => $object_id]);
198 $item_id = Item::searchByLink($object_id);
200 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
204 $id = Processor::fetchMissingActivity($object_id, [], $actor);
206 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
210 $item_id = Item::searchByLink($object_id);
212 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
214 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
219 * Fetches the object type for a given object id
221 * @param array $activity
222 * @param string $object_id Object ID of the the provided object
223 * @param integer $uid User ID
225 * @return string with object type
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @throws \ImagickException
229 private static function fetchObjectType($activity, $object_id, $uid = 0)
231 if (!empty($activity['as:object'])) {
232 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
233 if (!empty($object_type)) {
238 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
239 // We just assume "note" since it doesn't make a difference for the further processing
243 $profile = APContact::getByURL($object_id);
244 if (!empty($profile['type'])) {
245 APContact::unmarkForArchival($profile);
246 return 'as:' . $profile['type'];
249 $data = ActivityPub::fetchContent($object_id, $uid);
251 $object = JsonLD::compact($data);
252 $type = JsonLD::fetchElement($object, '@type');
262 * Prepare the object array
264 * @param array $activity Array with activity data
265 * @param integer $uid User ID
266 * @param boolean $push Message had been pushed to our system
267 * @param boolean $trust_source Do we trust the source?
269 * @return array with object data
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 * @throws \ImagickException
273 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
275 $id = JsonLD::fetchElement($activity, '@id');
276 if (!empty($id) && !$trust_source) {
277 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
278 if (!empty($fetched_activity)) {
279 $object = JsonLD::compact($fetched_activity);
280 $fetched_id = JsonLD::fetchElement($object, '@id');
281 if ($fetched_id == $id) {
282 Logger::info('Activity had been fetched successfully', ['id' => $id]);
283 $trust_source = true;
286 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
289 Logger::info('Activity could not been fetched', ['id' => $id]);
293 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
295 Logger::info('Empty actor', ['activity' => $activity]);
299 $type = JsonLD::fetchElement($activity, '@type');
301 // Fetch all receivers from to, cc, bto and bcc
302 $receiverdata = self::getReceivers($activity, $actor);
303 $receivers = $reception_types = [];
304 foreach ($receiverdata as $key => $data) {
305 $receivers[$key] = $data['uid'];
306 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
309 // When it is a delivery to a personal inbox we add that user to the receivers
311 $additional = [$uid => $uid];
312 $receivers = array_replace($receivers, $additional);
313 if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
314 $reception_types[$uid] = self::TARGET_BCC;
317 // We possibly need some user to fetch private content,
318 // so we fetch the first out ot the list.
319 $uid = self::getFirstUserFromReceivers($receivers);
322 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
323 if (empty($object_id)) {
324 Logger::log('No object found', Logger::DEBUG);
328 if (!is_string($object_id)) {
329 Logger::info('Invalid object id', ['object' => $object_id]);
333 $object_type = self::fetchObjectType($activity, $object_id, $uid);
335 // Fetch the content only on activities where this matters
336 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
337 // Always fetch on "Announce"
338 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
339 if (empty($object_data)) {
340 Logger::log("Object data couldn't be processed", Logger::DEBUG);
344 $object_data['object_id'] = $object_id;
346 if ($type == 'as:Announce') {
347 $object_data['push'] = false;
349 $object_data['push'] = $push;
352 // Test if it is an answer to a mail
353 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
354 $object_data['directmessage'] = true;
356 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
358 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
359 // Create a mostly empty array out of the activity data (instead of the object).
360 // This way we later don't have to check for the existence of ech individual array element.
361 $object_data = self::processObject($activity);
362 $object_data['name'] = $type;
363 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
364 $object_data['object_id'] = $object_id;
365 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
366 $object_data['push'] = $push;
367 } elseif (in_array($type, ['as:Add'])) {
369 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
370 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
371 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
372 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
373 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
374 $object_data['push'] = $push;
377 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
378 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
379 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
380 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
381 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
382 $object_data['push'] = $push;
384 // An Undo is done on the object of an object, so we need that type as well
385 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
386 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
390 $object_data = self::addActivityFields($object_data, $activity);
392 if (empty($object_data['object_type'])) {
393 $object_data['object_type'] = $object_type;
396 $object_data['type'] = $type;
397 $object_data['actor'] = $actor;
398 $object_data['item_receiver'] = $receivers;
399 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
400 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
402 $author = $object_data['author'] ?? $actor;
403 if (!empty($author) && !empty($object_data['id'])) {
404 $author_host = parse_url($author, PHP_URL_HOST);
405 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
406 if ($author_host == $id_host) {
407 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
409 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
410 $trust_source = false;
414 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
420 * Fetches the first user id from the receiver array
422 * @param array $receivers Array with receivers
423 * @return integer user id;
425 public static function getFirstUserFromReceivers($receivers)
427 foreach ($receivers as $receiver) {
428 if (!empty($receiver)) {
436 * Processes the activity object
438 * @param array $activity Array with activity data
439 * @param string $body
440 * @param integer $uid User ID
441 * @param boolean $trust_source Do we trust the source?
442 * @param boolean $push Message had been pushed to our system
445 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
447 $type = JsonLD::fetchElement($activity, '@type');
449 Logger::info('Empty type', ['activity' => $activity]);
453 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
454 Logger::info('Empty object', ['activity' => $activity]);
458 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
460 Logger::info('Empty actor', ['activity' => $activity]);
464 if (is_array($activity['as:object'])) {
465 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
470 // Test the provided signatures against the actor and "attributedTo"
472 if (!empty($attributed_to) && !empty($actor)) {
473 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
475 $trust_source = in_array($actor, $signer);
479 // $trust_source is called by reference and is set to true if the content was retrieved successfully
480 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
481 if (empty($object_data)) {
482 Logger::info('No object data found', ['activity' => $activity]);
486 if (!$trust_source) {
487 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
491 if (!empty($body) && empty($object_data['raw'])) {
492 $object_data['raw'] = $body;
495 // Internal flag for thread completion. See Processor.php
496 if (!empty($activity['thread-completion'])) {
497 $object_data['thread-completion'] = $activity['thread-completion'];
500 // Internal flag for posts that arrived via relay
501 if (!empty($activity['from-relay'])) {
502 $object_data['from-relay'] = $activity['from-relay'];
507 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
508 $item = ActivityPub\Processor::createItem($object_data);
509 ActivityPub\Processor::postItem($object_data, $item);
514 if ($object_data['object_type'] == 'as:tag') {
515 ActivityPub\Processor::addTag($object_data);
520 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
521 $object_data['thread-completion'] = Contact::getIdForURL($actor);
523 $item = ActivityPub\Processor::createItem($object_data);
528 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
529 ActivityPub\Processor::postItem($object_data, $item);
531 $announce_object_data = self::processObject($activity);
532 $announce_object_data['name'] = $type;
533 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
534 $announce_object_data['object_id'] = $object_data['object_id'];
535 $announce_object_data['object_type'] = $object_data['object_type'];
536 $announce_object_data['push'] = $push;
539 $announce_object_data['raw'] = $body;
542 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
547 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
548 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
553 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
554 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
558 case 'as:TentativeAccept':
559 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
560 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
565 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
566 ActivityPub\Processor::updateItem($object_data);
567 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
568 ActivityPub\Processor::updatePerson($object_data);
573 if ($object_data['object_type'] == 'as:Tombstone') {
574 ActivityPub\Processor::deleteItem($object_data);
575 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
576 ActivityPub\Processor::deletePerson($object_data);
581 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
582 ActivityPub\Processor::followUser($object_data);
583 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
584 $object_data['reply-to-id'] = $object_data['object_id'];
585 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
590 if ($object_data['object_type'] == 'as:Follow') {
591 ActivityPub\Processor::acceptFollowUser($object_data);
592 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
593 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
598 if ($object_data['object_type'] == 'as:Follow') {
599 ActivityPub\Processor::rejectFollowUser($object_data);
600 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
601 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
606 if (($object_data['object_type'] == 'as:Follow') &&
607 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
608 ActivityPub\Processor::undoFollowUser($object_data);
609 } elseif (($object_data['object_type'] == 'as:Accept') &&
610 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
611 ActivityPub\Processor::rejectFollowUser($object_data);
612 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
613 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
614 ActivityPub\Processor::undoActivity($object_data);
619 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
625 * Fetch the receiver list from an activity array
627 * @param array $activity
628 * @param string $actor
630 * @param boolean $fetch_unlisted
632 * @return array with receivers (user id)
635 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
637 $reply = $receivers = [];
639 // When it is an answer, we inherite the receivers from the parent
640 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
641 if (!empty($replyto)) {
644 // Fix possibly wrong item URI (could be an answer to a plink uri)
645 $fixedReplyTo = Item::getURIByLink($replyto);
646 if (!empty($fixedReplyTo)) {
647 $reply[] = $fixedReplyTo;
651 // Fetch all posts that refer to the object id
652 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
653 if (!empty($object_id)) {
654 $reply[] = $object_id;
657 if (!empty($reply)) {
658 $parents = Post::select(['uid'], ['uri' => $reply]);
659 while ($parent = Post::fetch($parents)) {
660 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
662 DBA::close($parents);
665 if (!empty($actor)) {
666 $profile = APContact::getByURL($actor);
667 $followers = $profile['followers'] ?? '';
668 $is_forum = ($actor['type'] ?? '') == 'Group';
669 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
671 Logger::info('Empty actor', ['activity' => $activity]);
676 // We have to prevent false follower assumptions upon thread completions
677 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
679 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
680 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
681 if (empty($receiver_list)) {
685 foreach ($receiver_list as $receiver) {
686 if ($receiver == self::PUBLIC_COLLECTION) {
687 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
690 // Add receiver "-1" for unlisted posts
691 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
692 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
695 // Fetch the receivers for the public and the followers collection
696 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
697 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
701 // Fetching all directly addressed receivers
702 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
703 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
704 if (!DBA::isResult($contact)) {
708 // Check if the potential receiver is following the actor
709 // Exception: The receiver is targetted via "to" or this is a comment
710 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
711 $networks = Protocol::FEDERATED;
712 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
713 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
715 // Forum posts are only accepted from forum contacts
716 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
717 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
720 if (!DBA::exists('contact', $condition)) {
725 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
726 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
729 $type = self::TARGET_TO;
732 $type = self::TARGET_CC;
735 $type = self::TARGET_BTO;
738 $type = self::TARGET_BCC;
742 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
747 self::switchContacts($receivers, $actor);
753 * Fetch the receiver list of a given actor
755 * @param string $actor
757 * @param array $receivers
758 * @param integer $target_type
760 * @return array with receivers (user id)
763 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
765 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
766 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
768 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
769 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
770 while ($contact = DBA::fetch($contacts)) {
771 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
772 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
775 DBA::close($contacts);
777 // The queries are split because of performance issues
778 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
779 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
780 while ($contact = DBA::fetch($contacts)) {
781 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
782 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
785 DBA::close($contacts);
790 * Tests if the contact is a valid receiver for this actor
792 * @param array $contact
793 * @param string $actor
796 * @return bool with receivers (user id)
799 private static function isValidReceiverForActor($contact, $tags)
801 // Are we following the contact? Then this is a valid receiver
802 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
806 // When the possible receiver isn't a community, then it is no valid receiver
807 $owner = User::getOwnerDataById($contact['uid']);
808 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
812 // Is the community account tagged?
813 foreach ($tags as $tag) {
814 if ($tag['type'] != 'Mention') {
818 if (Strings::compareLink($tag['href'], $owner['url'])) {
827 * Switches existing contacts to ActivityPub
829 * @param integer $cid Contact ID
830 * @param integer $uid User ID
831 * @param string $url Profile URL
832 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
833 * @throws \ImagickException
835 public static function switchContact($cid, $uid, $url)
837 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
838 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
842 if (Contact::updateFromProbe($cid)) {
843 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
846 // Send a new follow request to be sure that the connection still exists
847 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
848 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
849 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
858 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
859 * @throws \ImagickException
861 private static function switchContacts($receivers, $actor)
867 foreach ($receivers as $receiver) {
868 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
869 if (DBA::isResult($contact)) {
870 self::switchContact($contact['id'], $receiver['uid'], $actor);
873 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
874 if (DBA::isResult($contact)) {
875 self::switchContact($contact['id'], $receiver['uid'], $actor);
883 * @param $object_data
884 * @param array $activity
888 private static function addActivityFields($object_data, $activity)
890 if (!empty($activity['published']) && empty($object_data['published'])) {
891 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
894 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
895 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
898 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
899 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
901 if (!empty($object_data['object_id'])) {
902 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
903 $objectId = Item::getURIByLink($object_data['object_id']);
904 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
905 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
906 $object_data['object_id'] = $objectId;
914 * Fetches the object data from external ressources if needed
916 * @param string $object_id Object ID of the the provided object
917 * @param array $object The provided object array
918 * @param boolean $trust_source Do we trust the provided object?
919 * @param integer $uid User ID for the signature that we use to fetch data
921 * @return array|false with trusted and valid object data
922 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
923 * @throws \ImagickException
925 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
927 // By fetching the type we check if the object is complete.
928 $type = JsonLD::fetchElement($object, '@type');
930 if (!$trust_source || empty($type)) {
931 $data = ActivityPub::fetchContent($object_id, $uid);
933 $object = JsonLD::compact($data);
934 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
936 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
938 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
939 if (!DBA::isResult($item)) {
940 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
943 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
944 $data = ActivityPub\Transmitter::createNote($item);
945 $object = JsonLD::compact($data);
948 $id = JsonLD::fetchElement($object, '@id');
950 Logger::info('Empty id');
954 if ($id != $object_id) {
955 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
959 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
962 $type = JsonLD::fetchElement($object, '@type');
964 Logger::info('Empty type');
968 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
969 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
970 $object_data = self::processObject($object);
973 $object_data['raw'] = json_encode($data);
978 if ($type == 'as:Announce') {
979 $object_id = JsonLD::fetchElement($object, 'object', '@id');
980 if (empty($object_id) || !is_string($object_id)) {
983 return self::fetchObject($object_id, [], false, $uid);
986 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
991 * Converts the language element (Used by Peertube)
993 * @param array $languages
994 * @return array Languages
996 public static function processLanguages(array $languages)
998 if (empty($languages)) {
1002 $language_list = [];
1004 foreach ($languages as $language) {
1005 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1006 $language_list[$language['_:identifier']] = $language['as:name'];
1009 return $language_list;
1013 * Convert tags from JSON-LD format into a simplified format
1015 * @param array $tags Tags in JSON-LD format
1017 * @return array with tags in a simplified format
1019 public static function processTags(array $tags)
1023 foreach ($tags as $tag) {
1028 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1029 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1030 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1032 if (empty($element['type'])) {
1036 if (empty($element['href'])) {
1037 $element['href'] = $element['name'];
1040 $taglist[] = $element;
1046 * Convert emojis from JSON-LD format into a simplified format
1048 * @param array $emojis
1049 * @return array with emojis in a simplified format
1051 private static function processEmojis(array $emojis)
1055 foreach ($emojis as $emoji) {
1056 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1060 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1061 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1064 $emojilist[] = $element;
1071 * Convert attachments from JSON-LD format into a simplified format
1073 * @param array $attachments Attachments in JSON-LD format
1075 * @return array Attachments in a simplified format
1077 private static function processAttachments(array $attachments)
1081 // Removes empty values
1082 $attachments = array_filter($attachments);
1084 foreach ($attachments as $attachment) {
1085 switch (JsonLD::fetchElement($attachment, '@type')) {
1090 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1091 foreach ($urls as $url) {
1092 // Single scalar URL case
1093 if (is_string($url)) {
1098 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1099 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1100 if (Strings::startsWith($mediaType, 'image')) {
1109 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1110 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1112 'image' => $pageImage,
1117 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1118 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1119 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1120 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1124 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1125 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1126 $imagePreviewUrl = null;
1128 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1129 $imageVariants = [];
1130 $previewVariants = [];
1131 foreach ($urls as $url) {
1132 // Scalar URL, no discrimination possible
1133 if (is_string($url)) {
1134 $imageFullUrl = $url;
1138 // Not sure what to do with a different Link media type than the base Image, we skip
1139 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1143 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1145 // Default URL choice if no discriminating width is provided
1146 $imageFullUrl = $href ?? $imageFullUrl;
1148 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1150 if ($href && $width) {
1151 $imageVariants[$width] = $href;
1152 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1153 $previewVariants[abs(632 - $width)] = $href;
1157 if ($imageVariants) {
1158 // Taking the maximum size image
1159 ksort($imageVariants);
1160 $imageFullUrl = array_pop($imageVariants);
1162 // Taking the minimum number distance to the target distance
1163 ksort($previewVariants);
1164 $imagePreviewUrl = array_shift($previewVariants);
1167 unset($imageVariants);
1168 unset($previewVariants);
1172 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1173 'mediaType' => $mediaType,
1174 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1175 'url' => $imageFullUrl,
1176 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1181 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1182 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1183 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1184 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1193 * Fetch the original source or content with the "language" Markdown or HTML
1195 * @param array $object
1196 * @param array $object_data
1199 * @throws \Exception
1201 private static function getSource($object, $object_data)
1203 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1204 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1205 if (!empty($object_data['source'])) {
1206 return $object_data;
1209 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1210 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1211 if (!empty($object_data['source'])) {
1212 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1213 return $object_data;
1216 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1217 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1218 if (!empty($object_data['source'])) {
1219 $object_data['source'] = HTML::toBBCode($object_data['source']);
1220 return $object_data;
1223 return $object_data;
1227 * Check if the "as:url" element is an array with multiple links
1228 * This is the case with audio and video posts.
1229 * Then the links are added as attachments
1231 * @param array $object The raw object
1232 * @param array $object_data The parsed object data for later processing
1233 * @return array the object data
1235 private static function processAttachmentUrls(array $object, array $object_data) {
1236 // Check if this is some url with multiple links
1237 if (empty($object['as:url'])) {
1238 return $object_data;
1241 $urls = $object['as:url'];
1242 $keys = array_keys($urls);
1243 if (!is_numeric(array_pop($keys))) {
1244 return $object_data;
1249 foreach ($urls as $url) {
1250 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1254 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1259 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1260 if (empty($mediatype)) {
1264 if ($mediatype == 'text/html') {
1265 $object_data['alternate-url'] = $href;
1268 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1270 if ($filetype == 'audio') {
1271 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1272 } elseif ($filetype == 'video') {
1273 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1274 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1275 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1276 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1277 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1279 // For Torrent links we always store the highest resolution
1280 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1284 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1288 foreach ($attachments as $type => $attachment) {
1289 $object_data['attachments'][] = ['type' => $type,
1290 'mediaType' => $attachment['type'],
1291 'height' => $attachment['height'],
1292 'size' => $attachment['size'],
1294 'url' => $attachment['url']];
1296 return $object_data;
1300 * Fetches data from the object part of an activity
1302 * @param array $object
1305 * @throws \Exception
1307 private static function processObject($object)
1309 if (!JsonLD::fetchElement($object, '@id')) {
1314 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1315 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1316 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1318 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1319 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1320 $object_data['reply-to-id'] = $object_data['id'];
1322 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1323 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1324 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1325 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1326 $object_data['reply-to-id'] = $replyToId;
1330 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1331 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1333 if (empty($object_data['updated'])) {
1334 $object_data['updated'] = $object_data['published'];
1337 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1338 $object_data['published'] = $object_data['updated'];
1341 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1342 if (empty($actor)) {
1343 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1346 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1347 $location = JsonLD::fetchElement($location, 'location', '@value');
1349 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1350 // down to HTML and then finally format to plaintext.
1351 $location = Markdown::convert($location);
1352 $location = BBCode::convert($location);
1353 $location = HTML::toPlaintext($location);
1356 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1357 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1358 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1359 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1360 $object_data['actor'] = $object_data['author'] = $actor;
1361 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1362 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1363 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1364 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1365 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1366 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1367 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1368 $object_data = self::getSource($object, $object_data);
1369 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1370 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1371 $object_data['adjust'] = JsonLD::fetchElement($object, 'dfrn:adjust', '@value');
1372 $object_data['location'] = $location;
1373 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1374 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1375 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1376 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1377 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1378 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1379 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1380 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1381 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1382 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1383 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1385 // Special treatment for Hubzilla links
1386 if (is_array($object_data['alternate-url'])) {
1387 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1389 if (!is_string($object_data['alternate-url'])) {
1390 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1394 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1395 $object_data = self::processAttachmentUrls($object, $object_data);
1398 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1399 $receivers = $reception_types = [];
1400 foreach ($receiverdata as $key => $data) {
1401 $receivers[$key] = $data['uid'];
1402 $reception_types[$data['uid']] = $data['type'] ?? 0;
1405 $object_data['receiver'] = $receivers;
1406 $object_data['reception_type'] = $reception_types;
1408 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1409 unset($object_data['receiver'][-1]);
1410 unset($object_data['reception_type'][-1]);
1412 // Common object data:
1415 // @context, type, actor, signature, mediaType, duration, replies, icon
1417 // Also missing: (Defined in the standard, but currently unused)
1418 // audience, preview, endTime, startTime, image
1423 // contentMap, announcement_count, announcements, context_id, likes, like_count
1424 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1429 // category, licence, language, commentsEnabled
1432 // views, waitTranscoding, state, support, subtitleLanguage
1433 // likes, dislikes, shares, comments
1435 return $object_data;