3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Model\Contact;
31 use Friendica\Model\APContact;
32 use Friendica\Model\Item;
33 use Friendica\Model\User;
34 use Friendica\Protocol\Activity;
35 use Friendica\Protocol\ActivityPub;
36 use Friendica\Util\HTTPSignature;
37 use Friendica\Util\JsonLD;
38 use Friendica\Util\LDSignature;
39 use Friendica\Util\Strings;
42 * ActivityPub Receiver Protocol class
47 * Check what this is meant to do:
56 const PUBLIC_COLLECTION = 'as:Public';
57 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
58 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio'];
59 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
61 const TARGET_UNKNOWN = 0;
66 const TARGET_FOLLOWER = 5;
67 const TARGET_ANSWER = 6;
68 const TARGET_GLOBAL = 7;
71 * Checks if the web request is done for the AP protocol
73 * @return bool is it AP?
75 public static function isRequest()
77 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
78 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
82 * Checks incoming message from the inbox
86 * @param integer $uid User ID
89 public static function processInbox($body, $header, $uid)
91 $activity = json_decode($body, true);
92 if (empty($activity)) {
93 Logger::warning('Invalid body.');
97 $ldactivity = JsonLD::compact($activity);
99 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
101 $apcontact = APContact::getByURL($actor);
102 if (!empty($apcontact) && ($apcontact['type'] == 'Application') && ($apcontact['nick'] == 'relay')) {
103 self::processRelayPost($ldactivity, $actor);
107 $http_signer = HTTPSignature::getSigner($body, $header);
108 if (empty($http_signer)) {
109 Logger::warning('Invalid HTTP signature, message will be discarded.');
112 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
115 $signer = [$http_signer];
117 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
119 if (LDSignature::isSigned($activity)) {
120 $ld_signer = LDSignature::getSigner($activity);
121 if (empty($ld_signer)) {
122 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
123 } elseif ($ld_signer != $http_signer) {
124 $signer[] = $ld_signer;
126 if (!empty($ld_signer && ($actor == $http_signer))) {
127 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
128 $trust_source = true;
129 } elseif (!empty($ld_signer)) {
130 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
131 $trust_source = true;
132 } elseif ($actor == $http_signer) {
133 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
134 $trust_source = true;
136 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
137 $trust_source = false;
139 } elseif ($actor == $http_signer) {
140 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
141 $trust_source = true;
143 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
144 $trust_source = false;
147 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
151 * Process incoming posts from relays
153 * @param array $activity
154 * @param string $actor
157 private static function processRelayPost(array $activity, string $actor)
159 $type = JsonLD::fetchElement($activity, '@type');
161 Logger::info('Empty type', ['activity' => $activity]);
165 if ($type != 'as:Announce') {
166 Logger::info('Not an announcement', ['activity' => $activity]);
170 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
171 if (empty($object_id)) {
172 Logger::info('No object id found', ['activity' => $activity]);
176 Logger::info('Got relayed message id', ['id' => $object_id]);
178 $item_id = Item::searchByLink($object_id);
180 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
184 Processor::fetchMissingActivity($object_id, [], $actor);
186 $item_id = Item::searchByLink($object_id);
188 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
190 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
195 * Fetches the object type for a given object id
197 * @param array $activity
198 * @param string $object_id Object ID of the the provided object
199 * @param integer $uid User ID
201 * @return string with object type
202 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
203 * @throws \ImagickException
205 private static function fetchObjectType($activity, $object_id, $uid = 0)
207 if (!empty($activity['as:object'])) {
208 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
209 if (!empty($object_type)) {
214 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
215 // We just assume "note" since it doesn't make a difference for the further processing
219 $profile = APContact::getByURL($object_id);
220 if (!empty($profile['type'])) {
221 return 'as:' . $profile['type'];
224 $data = ActivityPub::fetchContent($object_id, $uid);
226 $object = JsonLD::compact($data);
227 $type = JsonLD::fetchElement($object, '@type');
237 * Prepare the object array
239 * @param array $activity Array with activity data
240 * @param integer $uid User ID
241 * @param boolean $push Message had been pushed to our system
242 * @param boolean $trust_source Do we trust the source?
244 * @return array with object data
245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
246 * @throws \ImagickException
248 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
250 $id = JsonLD::fetchElement($activity, '@id');
251 if (!empty($id) && !$trust_source) {
252 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
253 if (!empty($fetched_activity)) {
254 $object = JsonLD::compact($fetched_activity);
255 $fetched_id = JsonLD::fetchElement($object, '@id');
256 if ($fetched_id == $id) {
257 Logger::info('Activity had been fetched successfully', ['id' => $id]);
258 $trust_source = true;
261 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
264 Logger::info('Activity could not been fetched', ['id' => $id]);
268 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
270 Logger::info('Empty actor', ['activity' => $activity]);
274 $type = JsonLD::fetchElement($activity, '@type');
276 // Fetch all receivers from to, cc, bto and bcc
277 $receiverdata = self::getReceivers($activity, $actor);
278 $receivers = $reception_types = [];
279 foreach ($receiverdata as $key => $data) {
280 $receivers[$key] = $data['uid'];
281 $reception_types[$data['uid']] = $data['type'] ?? 0;
284 // When it is a delivery to a personal inbox we add that user to the receivers
286 $additional = ['uid:' . $uid => $uid];
287 $receivers = array_merge($receivers, $additional);
288 if (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
289 $reception_types[$uid] = self::TARGET_BCC;
292 // We possibly need some user to fetch private content,
293 // so we fetch the first out ot the list.
294 $uid = self::getFirstUserFromReceivers($receivers);
297 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
298 if (empty($object_id)) {
299 Logger::log('No object found', Logger::DEBUG);
303 if (!is_string($object_id)) {
304 Logger::info('Invalid object id', ['object' => $object_id]);
308 $object_type = self::fetchObjectType($activity, $object_id, $uid);
310 // Fetch the content only on activities where this matters
311 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
312 // Always fetch on "Announce"
313 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
314 if (empty($object_data)) {
315 Logger::log("Object data couldn't be processed", Logger::DEBUG);
319 $object_data['object_id'] = $object_id;
321 if ($type == 'as:Announce') {
322 $object_data['push'] = false;
324 $object_data['push'] = $push;
327 // Test if it is an answer to a mail
328 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
329 $object_data['directmessage'] = true;
331 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
333 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
334 // Create a mostly empty array out of the activity data (instead of the object).
335 // This way we later don't have to check for the existence of ech individual array element.
336 $object_data = self::processObject($activity);
337 $object_data['name'] = $type;
338 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
339 $object_data['object_id'] = $object_id;
340 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
341 } elseif (in_array($type, ['as:Add'])) {
343 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
344 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
345 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
346 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
347 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
350 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
351 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
352 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
353 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
354 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
356 // An Undo is done on the object of an object, so we need that type as well
357 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
358 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
362 $object_data = self::addActivityFields($object_data, $activity);
364 if (empty($object_data['object_type'])) {
365 $object_data['object_type'] = $object_type;
368 $object_data['type'] = $type;
369 $object_data['actor'] = $actor;
370 $object_data['item_receiver'] = $receivers;
371 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
372 $object_data['reception_type'] = array_merge($object_data['reception_type'] ?? [], $reception_types);
374 $author = $object_data['author'] ?? $actor;
375 if (!empty($author) && !empty($object_data['id'])) {
376 $author_host = parse_url($author, PHP_URL_HOST);
377 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
378 if ($author_host == $id_host) {
379 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
381 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
382 $trust_source = false;
386 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
392 * Fetches the first user id from the receiver array
394 * @param array $receivers Array with receivers
395 * @return integer user id;
397 public static function getFirstUserFromReceivers($receivers)
399 foreach ($receivers as $receiver) {
400 if (!empty($receiver)) {
408 * Processes the activity object
410 * @param array $activity Array with activity data
411 * @param string $body
412 * @param integer $uid User ID
413 * @param boolean $trust_source Do we trust the source?
414 * @param boolean $push Message had been pushed to our system
417 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
419 $type = JsonLD::fetchElement($activity, '@type');
421 Logger::info('Empty type', ['activity' => $activity]);
425 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
426 Logger::info('Empty object', ['activity' => $activity]);
430 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
432 Logger::info('Empty actor', ['activity' => $activity]);
436 if (is_array($activity['as:object'])) {
437 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
442 // Test the provided signatures against the actor and "attributedTo"
444 if (!empty($attributed_to) && !empty($actor)) {
445 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
447 $trust_source = in_array($actor, $signer);
451 // $trust_source is called by reference and is set to true if the content was retrieved successfully
452 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
453 if (empty($object_data)) {
454 Logger::info('No object data found', ['activity' => $activity]);
458 if (!$trust_source) {
459 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
463 if (!empty($body) && empty($object_data['raw'])) {
464 $object_data['raw'] = $body;
467 // Internal flag for thread completion. See Processor.php
468 if (!empty($activity['thread-completion'])) {
469 $object_data['thread-completion'] = $activity['thread-completion'];
472 // Internal flag for posts that arrived via relay
473 if (!empty($activity['from-relay'])) {
474 $object_data['from-relay'] = $activity['from-relay'];
479 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
480 $item = ActivityPub\Processor::createItem($object_data);
481 ActivityPub\Processor::postItem($object_data, $item);
486 if ($object_data['object_type'] == 'as:tag') {
487 ActivityPub\Processor::addTag($object_data);
492 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
493 $object_data['thread-completion'] = true;
495 $item = ActivityPub\Processor::createItem($object_data);
500 $item['post-type'] = Item::PT_ANNOUNCEMENT;
501 ActivityPub\Processor::postItem($object_data, $item);
503 $announce_object_data = self::processObject($activity);
504 $announce_object_data['name'] = $type;
505 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
506 $announce_object_data['object_id'] = $object_data['object_id'];
507 $announce_object_data['object_type'] = $object_data['object_type'];
508 $announce_object_data['push'] = $push;
511 $announce_object_data['raw'] = $body;
514 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
519 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
520 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
525 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
526 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
530 case 'as:TentativeAccept':
531 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
532 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
537 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
538 ActivityPub\Processor::updateItem($object_data);
539 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
540 ActivityPub\Processor::updatePerson($object_data);
545 if ($object_data['object_type'] == 'as:Tombstone') {
546 ActivityPub\Processor::deleteItem($object_data);
547 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
548 ActivityPub\Processor::deletePerson($object_data);
553 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
554 ActivityPub\Processor::followUser($object_data);
555 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
556 $object_data['reply-to-id'] = $object_data['object_id'];
557 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
562 if ($object_data['object_type'] == 'as:Follow') {
563 ActivityPub\Processor::acceptFollowUser($object_data);
564 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
565 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
570 if ($object_data['object_type'] == 'as:Follow') {
571 ActivityPub\Processor::rejectFollowUser($object_data);
572 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
573 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
578 if (($object_data['object_type'] == 'as:Follow') &&
579 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
580 ActivityPub\Processor::undoFollowUser($object_data);
581 } elseif (($object_data['object_type'] == 'as:Accept') &&
582 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
583 ActivityPub\Processor::rejectFollowUser($object_data);
584 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
585 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
586 ActivityPub\Processor::undoActivity($object_data);
591 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
597 * Fetch the receiver list from an activity array
599 * @param array $activity
600 * @param string $actor
602 * @param boolean $fetch_unlisted
604 * @return array with receivers (user id)
607 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
609 $reply = $receivers = [];
611 // When it is an answer, we inherite the receivers from the parent
612 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
613 if (!empty($replyto)) {
616 // Fix possibly wrong item URI (could be an answer to a plink uri)
617 $fixedReplyTo = Item::getURIByLink($replyto);
618 if (!empty($fixedReplyTo)) {
619 $reply[] = $fixedReplyTo;
623 // Fetch all posts that refer to the object id
624 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
625 if (!empty($object_id)) {
626 $reply[] = $object_id;
629 if (!empty($reply)) {
630 $parents = Item::select(['uid'], ['uri' => $reply]);
631 while ($parent = Item::fetch($parents)) {
632 $receivers['uid:' . $parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
636 if (!empty($actor)) {
637 $profile = APContact::getByURL($actor);
638 $followers = $profile['followers'] ?? '';
640 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
642 Logger::info('Empty actor', ['activity' => $activity]);
646 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
647 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
648 if (empty($receiver_list)) {
652 foreach ($receiver_list as $receiver) {
653 if ($receiver == self::PUBLIC_COLLECTION) {
654 $receivers['uid:0'] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
657 // Add receiver "-1" for unlisted posts
658 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
659 $receivers['uid:-1'] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
662 // Fetch the receivers for the public and the followers collection
663 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
664 $receivers = self::getReceiverForActor($actor, $tags, $receivers);
668 // Fetching all directly addressed receivers
669 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
670 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
671 if (!DBA::isResult($contact)) {
675 // Check if the potential receiver is following the actor
676 // Exception: The receiver is targetted via "to" or this is a comment
677 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
678 $networks = Protocol::FEDERATED;
679 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
680 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
682 // Forum posts are only accepted from forum contacts
683 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
684 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
687 if (!DBA::exists('contact', $condition)) {
692 $type = $receivers['uid:' . $contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
693 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
696 $type = self::TARGET_TO;
699 $type = self::TARGET_CC;
702 $type = self::TARGET_BTO;
705 $type = self::TARGET_BCC;
709 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
714 self::switchContacts($receivers, $actor);
720 * Fetch the receiver list of a given actor
722 * @param string $actor
725 * @return array with receivers (user id)
728 private static function getReceiverForActor($actor, $tags, $receivers)
730 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
731 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
733 $condition = DBA::mergeConditions($basecondition, ['nurl' => Strings::normaliseLink($actor)]);
734 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
735 while ($contact = DBA::fetch($contacts)) {
736 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
737 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
740 DBA::close($contacts);
742 // The queries are split because of performance issues
743 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?)", Strings::normaliseLink($actor), $actor]);
744 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
745 while ($contact = DBA::fetch($contacts)) {
746 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
747 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
750 DBA::close($contacts);
755 * Tests if the contact is a valid receiver for this actor
757 * @param array $contact
758 * @param string $actor
761 * @return bool with receivers (user id)
764 private static function isValidReceiverForActor($contact, $actor, $tags)
766 // Public contacts are no valid receiver
767 if ($contact['uid'] == 0) {
771 // Are we following the contact? Then this is a valid receiver
772 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
776 // When the possible receiver isn't a community, then it is no valid receiver
777 $owner = User::getOwnerDataById($contact['uid']);
778 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
782 // Is the community account tagged?
783 foreach ($tags as $tag) {
784 if ($tag['type'] != 'Mention') {
788 if ($tag['href'] == $owner['url']) {
797 * Switches existing contacts to ActivityPub
799 * @param integer $cid Contact ID
800 * @param integer $uid User ID
801 * @param string $url Profile URL
802 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
803 * @throws \ImagickException
805 public static function switchContact($cid, $uid, $url)
807 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
808 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
812 if (Contact::updateFromProbe($cid)) {
813 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
816 // Send a new follow request to be sure that the connection still exists
817 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
818 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
819 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
828 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
829 * @throws \ImagickException
831 private static function switchContacts($receivers, $actor)
837 foreach ($receivers as $receiver) {
838 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
839 if (DBA::isResult($contact)) {
840 self::switchContact($contact['id'], $receiver['uid'], $actor);
843 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
844 if (DBA::isResult($contact)) {
845 self::switchContact($contact['id'], $receiver['uid'], $actor);
853 * @param $object_data
854 * @param array $activity
858 private static function addActivityFields($object_data, $activity)
860 if (!empty($activity['published']) && empty($object_data['published'])) {
861 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
864 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
865 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
868 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
869 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
871 if (!empty($object_data['object_id'])) {
872 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
873 $objectId = Item::getURIByLink($object_data['object_id']);
874 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
875 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
876 $object_data['object_id'] = $objectId;
884 * Fetches the object data from external ressources if needed
886 * @param string $object_id Object ID of the the provided object
887 * @param array $object The provided object array
888 * @param boolean $trust_source Do we trust the provided object?
889 * @param integer $uid User ID for the signature that we use to fetch data
891 * @return array|false with trusted and valid object data
892 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
893 * @throws \ImagickException
895 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
897 // By fetching the type we check if the object is complete.
898 $type = JsonLD::fetchElement($object, '@type');
900 if (!$trust_source || empty($type)) {
901 $data = ActivityPub::fetchContent($object_id, $uid);
903 $object = JsonLD::compact($data);
904 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
906 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
908 $item = Item::selectFirst([], ['uri' => $object_id]);
909 if (!DBA::isResult($item)) {
910 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
913 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
914 $data = ActivityPub\Transmitter::createNote($item);
915 $object = JsonLD::compact($data);
918 $id = JsonLD::fetchElement($object, '@id');
920 Logger::info('Empty id');
924 if ($id != $object_id) {
925 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
929 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
932 $type = JsonLD::fetchElement($object, '@type');
934 Logger::info('Empty type');
938 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
939 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
940 $object_data = self::processObject($object);
943 $object_data['raw'] = json_encode($data);
948 if ($type == 'as:Announce') {
949 $object_id = JsonLD::fetchElement($object, 'object', '@id');
950 if (empty($object_id) || !is_string($object_id)) {
953 return self::fetchObject($object_id, [], false, $uid);
956 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
961 * Convert tags from JSON-LD format into a simplified format
963 * @param array $tags Tags in JSON-LD format
965 * @return array with tags in a simplified format
967 private static function processTags(array $tags)
971 foreach ($tags as $tag) {
976 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
977 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
978 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
980 if (empty($element['type'])) {
984 if (empty($element['href'])) {
985 $element['href'] = $element['name'];
988 $taglist[] = $element;
994 * Convert emojis from JSON-LD format into a simplified format
996 * @param array $emojis
997 * @return array with emojis in a simplified format
999 private static function processEmojis(array $emojis)
1003 foreach ($emojis as $emoji) {
1004 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1008 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1009 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1012 $emojilist[] = $element;
1019 * Convert attachments from JSON-LD format into a simplified format
1021 * @param array $attachments Attachments in JSON-LD format
1023 * @return array Attachments in a simplified format
1025 private static function processAttachments(array $attachments)
1029 // Removes empty values
1030 $attachments = array_filter($attachments);
1032 foreach ($attachments as $attachment) {
1033 switch (JsonLD::fetchElement($attachment, '@type')) {
1038 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1039 foreach ($urls as $url) {
1040 // Single scalar URL case
1041 if (is_string($url)) {
1046 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1047 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1048 if (Strings::startsWith($mediaType, 'image')) {
1057 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1058 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1060 'image' => $pageImage,
1065 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1066 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1067 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1068 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1072 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1073 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1074 $imagePreviewUrl = null;
1076 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1077 $imageVariants = [];
1078 $previewVariants = [];
1079 foreach ($urls as $url) {
1080 // Scalar URL, no discrimination possible
1081 if (is_string($url)) {
1082 $imageFullUrl = $url;
1086 // Not sure what to do with a different Link media type than the base Image, we skip
1087 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1091 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1093 // Default URL choice if no discriminating width is provided
1094 $imageFullUrl = $href ?? $imageFullUrl;
1096 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1098 if ($href && $width) {
1099 $imageVariants[$width] = $href;
1100 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1101 $previewVariants[abs(632 - $width)] = $href;
1105 if ($imageVariants) {
1106 // Taking the maximum size image
1107 ksort($imageVariants);
1108 $imageFullUrl = array_pop($imageVariants);
1110 // Taking the minimum number distance to the target distance
1111 ksort($previewVariants);
1112 $imagePreviewUrl = array_shift($previewVariants);
1115 unset($imageVariants);
1116 unset($previewVariants);
1120 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1121 'mediaType' => $mediaType,
1122 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1123 'url' => $imageFullUrl,
1124 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1129 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1130 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1131 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1132 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1141 * Fetch the original source or content with the "language" Markdown or HTML
1143 * @param array $object
1144 * @param array $object_data
1147 * @throws \Exception
1149 private static function getSource($object, $object_data)
1151 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1152 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1153 if (!empty($object_data['source'])) {
1154 return $object_data;
1157 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1158 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1159 if (!empty($object_data['source'])) {
1160 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1161 return $object_data;
1164 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1165 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1166 if (!empty($object_data['source'])) {
1167 $object_data['source'] = HTML::toBBCode($object_data['source']);
1168 return $object_data;
1171 return $object_data;
1175 * Check if the "as:url" element is an array with multiple links
1176 * This is the case with audio and video posts.
1177 * Then the links are added as attachments
1179 * @param array $object The raw object
1180 * @param array $object_data The parsed object data for later processing
1181 * @return array the object data
1183 private static function processAttachmentUrls(array $object, array $object_data) {
1184 // Check if this is some url with multiple links
1185 if (empty($object['as:url'])) {
1186 return $object_data;
1189 $urls = $object['as:url'];
1190 $keys = array_keys($urls);
1191 if (!is_numeric(array_pop($keys))) {
1192 return $object_data;
1197 foreach ($urls as $url) {
1198 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1202 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1207 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1208 if (empty($mediatype)) {
1212 if ($mediatype == 'text/html') {
1213 $object_data['alternate-url'] = $href;
1216 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1218 if ($filetype == 'audio') {
1219 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1220 } elseif ($filetype == 'video') {
1221 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1223 // We save bandwidth by using a moderate height
1224 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1225 if (!empty($attachments[$filetype]['height']) &&
1226 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1230 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1234 foreach ($attachments as $type => $attachment) {
1235 $object_data['attachments'][] = ['type' => $type,
1236 'mediaType' => $attachment['type'],
1238 'url' => $attachment['url']];
1240 return $object_data;
1244 * Fetches data from the object part of an activity
1246 * @param array $object
1249 * @throws \Exception
1251 private static function processObject($object)
1253 if (!JsonLD::fetchElement($object, '@id')) {
1258 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1259 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1260 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1262 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1263 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1264 $object_data['reply-to-id'] = $object_data['id'];
1266 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1267 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1268 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1269 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1270 $object_data['reply-to-id'] = $replyToId;
1274 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1275 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1277 if (empty($object_data['updated'])) {
1278 $object_data['updated'] = $object_data['published'];
1281 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1282 $object_data['published'] = $object_data['updated'];
1285 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1286 if (empty($actor)) {
1287 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1290 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1291 $location = JsonLD::fetchElement($location, 'location', '@value');
1293 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1294 // down to HTML and then finally format to plaintext.
1295 $location = Markdown::convert($location);
1296 $location = BBCode::convert($location);
1297 $location = HTML::toPlaintext($location);
1300 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1301 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1302 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1303 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1304 $object_data['actor'] = $object_data['author'] = $actor;
1305 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1306 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1307 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1308 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1309 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1310 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1311 $object_data = self::getSource($object, $object_data);
1312 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1313 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1314 $object_data['location'] = $location;
1315 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1316 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1317 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1318 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1319 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1320 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1321 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1322 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1323 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1324 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1326 // Special treatment for Hubzilla links
1327 if (is_array($object_data['alternate-url'])) {
1328 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1330 if (!is_string($object_data['alternate-url'])) {
1331 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1335 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1336 $object_data = self::processAttachmentUrls($object, $object_data);
1339 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1340 $receivers = $reception_types = [];
1341 foreach ($receiverdata as $key => $data) {
1342 $receivers[$key] = $data['uid'];
1343 $reception_types[$data['uid']] = $data['type'] ?? 0;
1346 $object_data['receiver'] = $receivers;
1347 $object_data['reception_type'] = $reception_types;
1349 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1350 unset($object_data['receiver']['uid:-1']);
1352 // Common object data:
1355 // @context, type, actor, signature, mediaType, duration, replies, icon
1357 // Also missing: (Defined in the standard, but currently unused)
1358 // audience, preview, endTime, startTime, image
1363 // contentMap, announcement_count, announcements, context_id, likes, like_count
1364 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1369 // category, licence, language, commentsEnabled
1372 // views, waitTranscoding, state, support, subtitleLanguage
1373 // likes, dislikes, shares, comments
1375 return $object_data;