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 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
337 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce']) || strpos($type, '#emojiReaction')) {
338 // Always fetch on "Announce"
339 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
340 if (empty($object_data)) {
341 Logger::log("Object data couldn't be processed", Logger::DEBUG);
345 $object_data['object_id'] = $object_id;
347 if ($type == 'as:Announce') {
348 $object_data['push'] = false;
350 $object_data['push'] = $push;
353 // Test if it is an answer to a mail
354 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
355 $object_data['directmessage'] = true;
357 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
359 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
360 // Create a mostly empty array out of the activity data (instead of the object).
361 // This way we later don't have to check for the existence of ech individual array element.
362 $object_data = self::processObject($activity);
363 $object_data['name'] = $type;
364 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
365 $object_data['object_id'] = $object_id;
366 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
367 $object_data['push'] = $push;
368 } elseif (in_array($type, ['as:Add'])) {
370 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
371 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
372 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
373 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
374 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
375 $object_data['push'] = $push;
378 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
379 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
380 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
381 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
382 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
383 $object_data['push'] = $push;
385 // An Undo is done on the object of an object, so we need that type as well
386 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
387 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
391 $object_data = self::addActivityFields($object_data, $activity);
393 if (empty($object_data['object_type'])) {
394 $object_data['object_type'] = $object_type;
397 $object_data['type'] = $type;
398 $object_data['actor'] = $actor;
399 $object_data['item_receiver'] = $receivers;
400 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
401 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
403 $author = $object_data['author'] ?? $actor;
404 if (!empty($author) && !empty($object_data['id'])) {
405 $author_host = parse_url($author, PHP_URL_HOST);
406 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
407 if ($author_host == $id_host) {
408 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
410 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
411 $trust_source = false;
415 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
421 * Fetches the first user id from the receiver array
423 * @param array $receivers Array with receivers
424 * @return integer user id;
426 public static function getFirstUserFromReceivers($receivers)
428 foreach ($receivers as $receiver) {
429 if (!empty($receiver)) {
437 * Processes the activity object
439 * @param array $activity Array with activity data
440 * @param string $body
441 * @param integer $uid User ID
442 * @param boolean $trust_source Do we trust the source?
443 * @param boolean $push Message had been pushed to our system
446 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
448 $type = JsonLD::fetchElement($activity, '@type');
450 Logger::info('Empty type', ['activity' => $activity]);
454 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
455 Logger::info('Empty object', ['activity' => $activity]);
459 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
461 Logger::info('Empty actor', ['activity' => $activity]);
465 if (is_array($activity['as:object'])) {
466 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
471 // Test the provided signatures against the actor and "attributedTo"
473 if (!empty($attributed_to) && !empty($actor)) {
474 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
476 $trust_source = in_array($actor, $signer);
480 // $trust_source is called by reference and is set to true if the content was retrieved successfully
481 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
482 if (empty($object_data)) {
483 Logger::info('No object data found', ['activity' => $activity]);
487 if (!$trust_source) {
488 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
492 if (!empty($body) && empty($object_data['raw'])) {
493 $object_data['raw'] = $body;
496 // Internal flag for thread completion. See Processor.php
497 if (!empty($activity['thread-completion'])) {
498 $object_data['thread-completion'] = $activity['thread-completion'];
501 // Internal flag for posts that arrived via relay
502 if (!empty($activity['from-relay'])) {
503 $object_data['from-relay'] = $activity['from-relay'];
508 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
509 $item = ActivityPub\Processor::createItem($object_data);
510 ActivityPub\Processor::postItem($object_data, $item);
515 if ($object_data['object_type'] == 'as:tag') {
516 ActivityPub\Processor::addTag($object_data);
521 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
522 $object_data['thread-completion'] = Contact::getIdForURL($actor);
524 $item = ActivityPub\Processor::createItem($object_data);
529 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
530 ActivityPub\Processor::postItem($object_data, $item);
532 $announce_object_data = self::processObject($activity);
533 $announce_object_data['name'] = $type;
534 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
535 $announce_object_data['object_id'] = $object_data['object_id'];
536 $announce_object_data['object_type'] = $object_data['object_type'];
537 $announce_object_data['push'] = $push;
540 $announce_object_data['raw'] = $body;
543 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
548 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
549 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
554 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
555 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
559 case 'as:TentativeAccept':
560 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
561 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
566 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
567 ActivityPub\Processor::updateItem($object_data);
568 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
569 ActivityPub\Processor::updatePerson($object_data);
574 if ($object_data['object_type'] == 'as:Tombstone') {
575 ActivityPub\Processor::deleteItem($object_data);
576 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
577 ActivityPub\Processor::deletePerson($object_data);
582 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
583 ActivityPub\Processor::followUser($object_data);
584 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
585 $object_data['reply-to-id'] = $object_data['object_id'];
586 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
591 if ($object_data['object_type'] == 'as:Follow') {
592 ActivityPub\Processor::acceptFollowUser($object_data);
593 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
594 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
599 if ($object_data['object_type'] == 'as:Follow') {
600 ActivityPub\Processor::rejectFollowUser($object_data);
601 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
602 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
607 if (($object_data['object_type'] == 'as:Follow') &&
608 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
609 ActivityPub\Processor::undoFollowUser($object_data);
610 } elseif (($object_data['object_type'] == 'as:Accept') &&
611 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
612 ActivityPub\Processor::rejectFollowUser($object_data);
613 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
614 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
615 ActivityPub\Processor::undoActivity($object_data);
620 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
626 * Fetch the receiver list from an activity array
628 * @param array $activity
629 * @param string $actor
631 * @param boolean $fetch_unlisted
633 * @return array with receivers (user id)
636 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
638 $reply = $receivers = [];
640 // When it is an answer, we inherite the receivers from the parent
641 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
642 if (!empty($replyto)) {
645 // Fix possibly wrong item URI (could be an answer to a plink uri)
646 $fixedReplyTo = Item::getURIByLink($replyto);
647 if (!empty($fixedReplyTo)) {
648 $reply[] = $fixedReplyTo;
652 // Fetch all posts that refer to the object id
653 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
654 if (!empty($object_id)) {
655 $reply[] = $object_id;
658 if (!empty($reply)) {
659 $parents = Post::select(['uid'], ['uri' => $reply]);
660 while ($parent = Post::fetch($parents)) {
661 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
663 DBA::close($parents);
666 if (!empty($actor)) {
667 $profile = APContact::getByURL($actor);
668 $followers = $profile['followers'] ?? '';
669 $is_forum = ($actor['type'] ?? '') == 'Group';
670 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
672 Logger::info('Empty actor', ['activity' => $activity]);
677 // We have to prevent false follower assumptions upon thread completions
678 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
680 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
681 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
682 if (empty($receiver_list)) {
686 foreach ($receiver_list as $receiver) {
687 if ($receiver == self::PUBLIC_COLLECTION) {
688 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
691 // Add receiver "-1" for unlisted posts
692 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
693 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
696 // Fetch the receivers for the public and the followers collection
697 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
698 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
702 // Fetching all directly addressed receivers
703 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
704 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
705 if (!DBA::isResult($contact)) {
709 // Check if the potential receiver is following the actor
710 // Exception: The receiver is targetted via "to" or this is a comment
711 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
712 $networks = Protocol::FEDERATED;
713 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
714 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
716 // Forum posts are only accepted from forum contacts
717 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
718 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
721 if (!DBA::exists('contact', $condition)) {
726 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
727 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
730 $type = self::TARGET_TO;
733 $type = self::TARGET_CC;
736 $type = self::TARGET_BTO;
739 $type = self::TARGET_BCC;
743 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
748 self::switchContacts($receivers, $actor);
754 * Fetch the receiver list of a given actor
756 * @param string $actor
758 * @param array $receivers
759 * @param integer $target_type
761 * @return array with receivers (user id)
764 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
766 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
767 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
769 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
770 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
771 while ($contact = DBA::fetch($contacts)) {
772 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
773 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
776 DBA::close($contacts);
778 // The queries are split because of performance issues
779 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
780 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
781 while ($contact = DBA::fetch($contacts)) {
782 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
783 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
786 DBA::close($contacts);
791 * Tests if the contact is a valid receiver for this actor
793 * @param array $contact
794 * @param string $actor
797 * @return bool with receivers (user id)
800 private static function isValidReceiverForActor($contact, $tags)
802 // Are we following the contact? Then this is a valid receiver
803 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
807 // When the possible receiver isn't a community, then it is no valid receiver
808 $owner = User::getOwnerDataById($contact['uid']);
809 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
813 // Is the community account tagged?
814 foreach ($tags as $tag) {
815 if ($tag['type'] != 'Mention') {
819 if (Strings::compareLink($tag['href'], $owner['url'])) {
828 * Switches existing contacts to ActivityPub
830 * @param integer $cid Contact ID
831 * @param integer $uid User ID
832 * @param string $url Profile URL
833 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
834 * @throws \ImagickException
836 public static function switchContact($cid, $uid, $url)
838 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
839 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
843 if (Contact::updateFromProbe($cid)) {
844 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
847 // Send a new follow request to be sure that the connection still exists
848 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
849 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
850 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
859 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
860 * @throws \ImagickException
862 private static function switchContacts($receivers, $actor)
868 foreach ($receivers as $receiver) {
869 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
870 if (DBA::isResult($contact)) {
871 self::switchContact($contact['id'], $receiver['uid'], $actor);
874 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
875 if (DBA::isResult($contact)) {
876 self::switchContact($contact['id'], $receiver['uid'], $actor);
884 * @param $object_data
885 * @param array $activity
889 private static function addActivityFields($object_data, $activity)
891 if (!empty($activity['published']) && empty($object_data['published'])) {
892 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
895 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
896 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
899 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
900 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
902 if (!empty($object_data['object_id'])) {
903 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
904 $objectId = Item::getURIByLink($object_data['object_id']);
905 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
906 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
907 $object_data['object_id'] = $objectId;
915 * Fetches the object data from external ressources if needed
917 * @param string $object_id Object ID of the the provided object
918 * @param array $object The provided object array
919 * @param boolean $trust_source Do we trust the provided object?
920 * @param integer $uid User ID for the signature that we use to fetch data
922 * @return array|false with trusted and valid object data
923 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
924 * @throws \ImagickException
926 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
928 // By fetching the type we check if the object is complete.
929 $type = JsonLD::fetchElement($object, '@type');
931 if (!$trust_source || empty($type)) {
932 $data = ActivityPub::fetchContent($object_id, $uid);
934 $object = JsonLD::compact($data);
935 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
937 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
939 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
940 if (!DBA::isResult($item)) {
941 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
944 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
945 $data = ActivityPub\Transmitter::createNote($item);
946 $object = JsonLD::compact($data);
949 $id = JsonLD::fetchElement($object, '@id');
951 Logger::info('Empty id');
955 if ($id != $object_id) {
956 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
960 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
963 $type = JsonLD::fetchElement($object, '@type');
965 Logger::info('Empty type');
969 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
970 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
971 $object_data = self::processObject($object);
974 $object_data['raw'] = json_encode($data);
979 if ($type == 'as:Announce') {
980 $object_id = JsonLD::fetchElement($object, 'object', '@id');
981 if (empty($object_id) || !is_string($object_id)) {
984 return self::fetchObject($object_id, [], false, $uid);
987 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
992 * Converts the language element (Used by Peertube)
994 * @param array $languages
995 * @return array Languages
997 public static function processLanguages(array $languages)
999 if (empty($languages)) {
1003 $language_list = [];
1005 foreach ($languages as $language) {
1006 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1007 $language_list[$language['_:identifier']] = $language['as:name'];
1010 return $language_list;
1014 * Convert tags from JSON-LD format into a simplified format
1016 * @param array $tags Tags in JSON-LD format
1018 * @return array with tags in a simplified format
1020 public static function processTags(array $tags)
1024 foreach ($tags as $tag) {
1029 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1030 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1031 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1033 if (empty($element['type'])) {
1037 if (empty($element['href'])) {
1038 $element['href'] = $element['name'];
1041 $taglist[] = $element;
1047 * Convert emojis from JSON-LD format into a simplified format
1049 * @param array $emojis
1050 * @return array with emojis in a simplified format
1052 private static function processEmojis(array $emojis)
1056 foreach ($emojis as $emoji) {
1057 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1061 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1062 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1065 $emojilist[] = $element;
1072 * Convert attachments from JSON-LD format into a simplified format
1074 * @param array $attachments Attachments in JSON-LD format
1076 * @return array Attachments in a simplified format
1078 private static function processAttachments(array $attachments)
1082 // Removes empty values
1083 $attachments = array_filter($attachments);
1085 foreach ($attachments as $attachment) {
1086 switch (JsonLD::fetchElement($attachment, '@type')) {
1091 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1092 foreach ($urls as $url) {
1093 // Single scalar URL case
1094 if (is_string($url)) {
1099 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1100 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1101 if (Strings::startsWith($mediaType, 'image')) {
1110 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1111 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1113 'image' => $pageImage,
1117 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1118 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1119 $imagePreviewUrl = null;
1121 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1122 $imageVariants = [];
1123 $previewVariants = [];
1124 foreach ($urls as $url) {
1125 // Scalar URL, no discrimination possible
1126 if (is_string($url)) {
1127 $imageFullUrl = $url;
1131 // Not sure what to do with a different Link media type than the base Image, we skip
1132 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1136 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1138 // Default URL choice if no discriminating width is provided
1139 $imageFullUrl = $href ?? $imageFullUrl;
1141 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1143 if ($href && $width) {
1144 $imageVariants[$width] = $href;
1145 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1146 $previewVariants[abs(632 - $width)] = $href;
1150 if ($imageVariants) {
1151 // Taking the maximum size image
1152 ksort($imageVariants);
1153 $imageFullUrl = array_pop($imageVariants);
1155 // Taking the minimum number distance to the target distance
1156 ksort($previewVariants);
1157 $imagePreviewUrl = array_shift($previewVariants);
1160 unset($imageVariants);
1161 unset($previewVariants);
1165 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1166 'mediaType' => $mediaType,
1167 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1168 'url' => $imageFullUrl,
1169 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1174 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1175 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1176 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1177 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1178 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1179 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1180 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1189 * Fetch the original source or content with the "language" Markdown or HTML
1191 * @param array $object
1192 * @param array $object_data
1195 * @throws \Exception
1197 private static function getSource($object, $object_data)
1199 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1200 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1201 if (!empty($object_data['source'])) {
1202 return $object_data;
1205 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1206 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1207 if (!empty($object_data['source'])) {
1208 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1209 return $object_data;
1212 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1213 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1214 if (!empty($object_data['source'])) {
1215 $object_data['source'] = HTML::toBBCode($object_data['source']);
1216 return $object_data;
1219 return $object_data;
1223 * Extracts a potential alternate URL from a list of additional URL elements
1225 * @param array $urls
1228 private static function extractAlternateUrl(array $urls): string
1231 foreach ($urls as $key => $url) {
1232 // Not a list but a single URL element
1233 if (!is_numeric($key)) {
1237 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1241 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1246 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1247 if (empty($mediatype)) {
1251 if ($mediatype == 'text/html') {
1252 $alternateUrl = $href;
1256 return $alternateUrl;
1260 * Check if the "as:url" element is an array with multiple links
1261 * This is the case with audio and video posts.
1262 * Then the links are added as attachments
1264 * @param array $urls The object URL list
1265 * @return array an array of attachments
1267 private static function processAttachmentUrls(array $urls): array
1270 foreach ($urls as $key => $url) {
1271 // Not a list but a single URL element
1272 if (!is_numeric($key)) {
1276 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1280 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1285 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1286 if (empty($mediatype)) {
1290 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1292 if ($filetype == 'audio') {
1293 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1294 } elseif ($filetype == 'video') {
1295 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1296 // PeerTube audio-only track
1297 if ($height === 0) {
1301 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1302 // For embedded video we take the smallest available size
1303 if (!empty($attachments[$mediatype]['size']) && ($size > $attachments[$mediatype]['size'])) {
1307 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1308 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1309 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1311 // For Torrent links we always store the highest resolution
1312 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1316 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1317 } elseif ($mediatype == 'application/x-mpegURL') {
1318 // PeerTube exception, actual video link is in the tags of this URL element
1319 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1323 return $attachments;
1327 * Fetches data from the object part of an activity
1329 * @param array $object
1332 * @throws \Exception
1334 private static function processObject($object)
1336 if (!JsonLD::fetchElement($object, '@id')) {
1341 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1342 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1343 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1345 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1346 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1347 $object_data['reply-to-id'] = $object_data['id'];
1349 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1350 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1351 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1352 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1353 $object_data['reply-to-id'] = $replyToId;
1357 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1358 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1360 if (empty($object_data['updated'])) {
1361 $object_data['updated'] = $object_data['published'];
1364 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1365 $object_data['published'] = $object_data['updated'];
1368 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1369 if (empty($actor)) {
1370 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1373 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1374 $location = JsonLD::fetchElement($location, 'location', '@value');
1376 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1377 // down to HTML and then finally format to plaintext.
1378 $location = Markdown::convert($location);
1379 $location = BBCode::toPlaintext($location);
1382 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1383 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1384 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1385 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1386 $object_data['actor'] = $object_data['author'] = $actor;
1387 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1388 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1389 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1390 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1391 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1392 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1393 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1394 $object_data = self::getSource($object, $object_data);
1395 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1396 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1397 $object_data['adjust'] = JsonLD::fetchElement($object, 'dfrn:adjust', '@value');
1398 $object_data['location'] = $location;
1399 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1400 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1401 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1402 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1403 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1404 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1405 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1406 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1407 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1408 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1409 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1411 // Special treatment for Hubzilla links
1412 if (is_array($object_data['alternate-url'])) {
1413 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1415 if (!is_string($object_data['alternate-url'])) {
1416 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1420 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1421 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1423 $attachments = self::processAttachmentUrls($object['as:url'] ?? []);
1424 foreach ($attachments as $type => $attachment) {
1425 $object_data['attachments'][] = [
1427 'mediaType' => $attachment['type'],
1428 'height' => $attachment['height'],
1429 'size' => $attachment['size'],
1431 'url' => $attachment['url']
1436 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1437 $receivers = $reception_types = [];
1438 foreach ($receiverdata as $key => $data) {
1439 $receivers[$key] = $data['uid'];
1440 $reception_types[$data['uid']] = $data['type'] ?? 0;
1443 $object_data['receiver'] = $receivers;
1444 $object_data['reception_type'] = $reception_types;
1446 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1447 unset($object_data['receiver'][-1]);
1448 unset($object_data['reception_type'][-1]);
1450 // Common object data:
1453 // @context, type, actor, signature, mediaType, duration, replies, icon
1455 // Also missing: (Defined in the standard, but currently unused)
1456 // audience, preview, endTime, startTime, image
1461 // contentMap, announcement_count, announcements, context_id, likes, like_count
1462 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1467 // category, licence, language, commentsEnabled
1470 // views, waitTranscoding, state, support, subtitleLanguage
1471 // likes, dislikes, shares, comments
1473 return $object_data;