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 $contact = Contact::getByURL($actor);
177 if (empty($contact)) {
178 Logger::info('Relay contact not found', ['actor' => $actor]);
182 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
183 Logger::notice('Relay is no sharer', ['actor' => $actor]);
187 Logger::info('Got relayed message id', ['id' => $object_id]);
189 $item_id = Item::searchByLink($object_id);
191 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
195 $id = Processor::fetchMissingActivity($object_id, [], $actor);
197 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
201 $item_id = Item::searchByLink($object_id);
203 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
205 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
210 * Fetches the object type for a given object id
212 * @param array $activity
213 * @param string $object_id Object ID of the the provided object
214 * @param integer $uid User ID
216 * @return string with object type
217 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218 * @throws \ImagickException
220 private static function fetchObjectType($activity, $object_id, $uid = 0)
222 if (!empty($activity['as:object'])) {
223 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
224 if (!empty($object_type)) {
229 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
230 // We just assume "note" since it doesn't make a difference for the further processing
234 $profile = APContact::getByURL($object_id);
235 if (!empty($profile['type'])) {
236 return 'as:' . $profile['type'];
239 $data = ActivityPub::fetchContent($object_id, $uid);
241 $object = JsonLD::compact($data);
242 $type = JsonLD::fetchElement($object, '@type');
252 * Prepare the object array
254 * @param array $activity Array with activity data
255 * @param integer $uid User ID
256 * @param boolean $push Message had been pushed to our system
257 * @param boolean $trust_source Do we trust the source?
259 * @return array with object data
260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
261 * @throws \ImagickException
263 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
265 $id = JsonLD::fetchElement($activity, '@id');
266 if (!empty($id) && !$trust_source) {
267 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
268 if (!empty($fetched_activity)) {
269 $object = JsonLD::compact($fetched_activity);
270 $fetched_id = JsonLD::fetchElement($object, '@id');
271 if ($fetched_id == $id) {
272 Logger::info('Activity had been fetched successfully', ['id' => $id]);
273 $trust_source = true;
276 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
279 Logger::info('Activity could not been fetched', ['id' => $id]);
283 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
285 Logger::info('Empty actor', ['activity' => $activity]);
289 $type = JsonLD::fetchElement($activity, '@type');
291 // Fetch all receivers from to, cc, bto and bcc
292 $receiverdata = self::getReceivers($activity, $actor);
293 $receivers = $reception_types = [];
294 foreach ($receiverdata as $key => $data) {
295 $receivers[$key] = $data['uid'];
296 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
299 // When it is a delivery to a personal inbox we add that user to the receivers
301 $additional = [$uid => $uid];
302 $receivers = array_replace($receivers, $additional);
303 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]))) {
304 $reception_types[$uid] = self::TARGET_BCC;
307 // We possibly need some user to fetch private content,
308 // so we fetch the first out ot the list.
309 $uid = self::getFirstUserFromReceivers($receivers);
312 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
313 if (empty($object_id)) {
314 Logger::log('No object found', Logger::DEBUG);
318 if (!is_string($object_id)) {
319 Logger::info('Invalid object id', ['object' => $object_id]);
323 $object_type = self::fetchObjectType($activity, $object_id, $uid);
325 // Fetch the content only on activities where this matters
326 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
327 // Always fetch on "Announce"
328 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
329 if (empty($object_data)) {
330 Logger::log("Object data couldn't be processed", Logger::DEBUG);
334 $object_data['object_id'] = $object_id;
336 if ($type == 'as:Announce') {
337 $object_data['push'] = false;
339 $object_data['push'] = $push;
342 // Test if it is an answer to a mail
343 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
344 $object_data['directmessage'] = true;
346 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
348 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
349 // Create a mostly empty array out of the activity data (instead of the object).
350 // This way we later don't have to check for the existence of ech individual array element.
351 $object_data = self::processObject($activity);
352 $object_data['name'] = $type;
353 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
354 $object_data['object_id'] = $object_id;
355 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
356 } elseif (in_array($type, ['as:Add'])) {
358 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
359 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
360 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
361 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
362 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
365 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
366 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
367 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
368 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
369 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
371 // An Undo is done on the object of an object, so we need that type as well
372 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
373 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
377 $object_data = self::addActivityFields($object_data, $activity);
379 if (empty($object_data['object_type'])) {
380 $object_data['object_type'] = $object_type;
383 $object_data['type'] = $type;
384 $object_data['actor'] = $actor;
385 $object_data['item_receiver'] = $receivers;
386 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
387 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
389 $author = $object_data['author'] ?? $actor;
390 if (!empty($author) && !empty($object_data['id'])) {
391 $author_host = parse_url($author, PHP_URL_HOST);
392 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
393 if ($author_host == $id_host) {
394 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
396 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
397 $trust_source = false;
401 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
407 * Fetches the first user id from the receiver array
409 * @param array $receivers Array with receivers
410 * @return integer user id;
412 public static function getFirstUserFromReceivers($receivers)
414 foreach ($receivers as $receiver) {
415 if (!empty($receiver)) {
423 * Processes the activity object
425 * @param array $activity Array with activity data
426 * @param string $body
427 * @param integer $uid User ID
428 * @param boolean $trust_source Do we trust the source?
429 * @param boolean $push Message had been pushed to our system
432 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
434 $type = JsonLD::fetchElement($activity, '@type');
436 Logger::info('Empty type', ['activity' => $activity]);
440 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
441 Logger::info('Empty object', ['activity' => $activity]);
445 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
447 Logger::info('Empty actor', ['activity' => $activity]);
451 if (is_array($activity['as:object'])) {
452 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
457 // Test the provided signatures against the actor and "attributedTo"
459 if (!empty($attributed_to) && !empty($actor)) {
460 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
462 $trust_source = in_array($actor, $signer);
466 // $trust_source is called by reference and is set to true if the content was retrieved successfully
467 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
468 if (empty($object_data)) {
469 Logger::info('No object data found', ['activity' => $activity]);
473 if (!$trust_source) {
474 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
478 if (!empty($body) && empty($object_data['raw'])) {
479 $object_data['raw'] = $body;
482 // Internal flag for thread completion. See Processor.php
483 if (!empty($activity['thread-completion'])) {
484 $object_data['thread-completion'] = $activity['thread-completion'];
487 // Internal flag for posts that arrived via relay
488 if (!empty($activity['from-relay'])) {
489 $object_data['from-relay'] = $activity['from-relay'];
494 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
495 $item = ActivityPub\Processor::createItem($object_data);
496 ActivityPub\Processor::postItem($object_data, $item);
501 if ($object_data['object_type'] == 'as:tag') {
502 ActivityPub\Processor::addTag($object_data);
507 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
508 $object_data['thread-completion'] = Contact::getIdForURL($actor);
510 $item = ActivityPub\Processor::createItem($object_data);
515 $item['post-type'] = Item::PT_ANNOUNCEMENT;
516 ActivityPub\Processor::postItem($object_data, $item);
518 $announce_object_data = self::processObject($activity);
519 $announce_object_data['name'] = $type;
520 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
521 $announce_object_data['object_id'] = $object_data['object_id'];
522 $announce_object_data['object_type'] = $object_data['object_type'];
523 $announce_object_data['push'] = $push;
526 $announce_object_data['raw'] = $body;
529 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
534 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
535 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
540 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
541 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
545 case 'as:TentativeAccept':
546 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
547 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
552 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
553 ActivityPub\Processor::updateItem($object_data);
554 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
555 ActivityPub\Processor::updatePerson($object_data);
560 if ($object_data['object_type'] == 'as:Tombstone') {
561 ActivityPub\Processor::deleteItem($object_data);
562 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
563 ActivityPub\Processor::deletePerson($object_data);
568 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
569 ActivityPub\Processor::followUser($object_data);
570 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
571 $object_data['reply-to-id'] = $object_data['object_id'];
572 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
577 if ($object_data['object_type'] == 'as:Follow') {
578 ActivityPub\Processor::acceptFollowUser($object_data);
579 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
580 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
585 if ($object_data['object_type'] == 'as:Follow') {
586 ActivityPub\Processor::rejectFollowUser($object_data);
587 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
588 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
593 if (($object_data['object_type'] == 'as:Follow') &&
594 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
595 ActivityPub\Processor::undoFollowUser($object_data);
596 } elseif (($object_data['object_type'] == 'as:Accept') &&
597 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
598 ActivityPub\Processor::rejectFollowUser($object_data);
599 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
600 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
601 ActivityPub\Processor::undoActivity($object_data);
606 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
612 * Fetch the receiver list from an activity array
614 * @param array $activity
615 * @param string $actor
617 * @param boolean $fetch_unlisted
619 * @return array with receivers (user id)
622 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
624 $reply = $receivers = [];
626 // When it is an answer, we inherite the receivers from the parent
627 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
628 if (!empty($replyto)) {
631 // Fix possibly wrong item URI (could be an answer to a plink uri)
632 $fixedReplyTo = Item::getURIByLink($replyto);
633 if (!empty($fixedReplyTo)) {
634 $reply[] = $fixedReplyTo;
638 // Fetch all posts that refer to the object id
639 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
640 if (!empty($object_id)) {
641 $reply[] = $object_id;
644 if (!empty($reply)) {
645 $parents = Item::select(['uid'], ['uri' => $reply]);
646 while ($parent = Item::fetch($parents)) {
647 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
651 if (!empty($actor)) {
652 $profile = APContact::getByURL($actor);
653 $followers = $profile['followers'] ?? '';
655 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
657 Logger::info('Empty actor', ['activity' => $activity]);
661 // We have to prevent false follower assumptions upon thread completions
662 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
664 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
665 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
666 if (empty($receiver_list)) {
670 foreach ($receiver_list as $receiver) {
671 if ($receiver == self::PUBLIC_COLLECTION) {
672 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
675 // Add receiver "-1" for unlisted posts
676 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
677 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
680 // Fetch the receivers for the public and the followers collection
681 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
682 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
686 // Fetching all directly addressed receivers
687 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
688 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
689 if (!DBA::isResult($contact)) {
693 // Check if the potential receiver is following the actor
694 // Exception: The receiver is targetted via "to" or this is a comment
695 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
696 $networks = Protocol::FEDERATED;
697 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
698 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
700 // Forum posts are only accepted from forum contacts
701 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
702 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
705 if (!DBA::exists('contact', $condition)) {
710 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
711 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
714 $type = self::TARGET_TO;
717 $type = self::TARGET_CC;
720 $type = self::TARGET_BTO;
723 $type = self::TARGET_BCC;
727 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
732 self::switchContacts($receivers, $actor);
738 * Fetch the receiver list of a given actor
740 * @param string $actor
742 * @param array $receivers
743 * @param integer $target_type
745 * @return array with receivers (user id)
748 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
750 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
751 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
753 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
754 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
755 while ($contact = DBA::fetch($contacts)) {
756 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
757 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
760 DBA::close($contacts);
762 // The queries are split because of performance issues
763 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
764 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
765 while ($contact = DBA::fetch($contacts)) {
766 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
767 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
770 DBA::close($contacts);
775 * Tests if the contact is a valid receiver for this actor
777 * @param array $contact
778 * @param string $actor
781 * @return bool with receivers (user id)
784 private static function isValidReceiverForActor($contact, $tags)
786 // Are we following the contact? Then this is a valid receiver
787 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
791 // When the possible receiver isn't a community, then it is no valid receiver
792 $owner = User::getOwnerDataById($contact['uid']);
793 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
797 // Is the community account tagged?
798 foreach ($tags as $tag) {
799 if ($tag['type'] != 'Mention') {
803 if (Strings::compareLink($tag['href'], $owner['url'])) {
812 * Switches existing contacts to ActivityPub
814 * @param integer $cid Contact ID
815 * @param integer $uid User ID
816 * @param string $url Profile URL
817 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
818 * @throws \ImagickException
820 public static function switchContact($cid, $uid, $url)
822 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
823 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
827 if (Contact::updateFromProbe($cid)) {
828 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
831 // Send a new follow request to be sure that the connection still exists
832 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
833 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
834 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
843 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
844 * @throws \ImagickException
846 private static function switchContacts($receivers, $actor)
852 foreach ($receivers as $receiver) {
853 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
854 if (DBA::isResult($contact)) {
855 self::switchContact($contact['id'], $receiver['uid'], $actor);
858 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
859 if (DBA::isResult($contact)) {
860 self::switchContact($contact['id'], $receiver['uid'], $actor);
868 * @param $object_data
869 * @param array $activity
873 private static function addActivityFields($object_data, $activity)
875 if (!empty($activity['published']) && empty($object_data['published'])) {
876 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
879 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
880 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
883 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
884 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
886 if (!empty($object_data['object_id'])) {
887 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
888 $objectId = Item::getURIByLink($object_data['object_id']);
889 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
890 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
891 $object_data['object_id'] = $objectId;
899 * Fetches the object data from external ressources if needed
901 * @param string $object_id Object ID of the the provided object
902 * @param array $object The provided object array
903 * @param boolean $trust_source Do we trust the provided object?
904 * @param integer $uid User ID for the signature that we use to fetch data
906 * @return array|false with trusted and valid object data
907 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
908 * @throws \ImagickException
910 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
912 // By fetching the type we check if the object is complete.
913 $type = JsonLD::fetchElement($object, '@type');
915 if (!$trust_source || empty($type)) {
916 $data = ActivityPub::fetchContent($object_id, $uid);
918 $object = JsonLD::compact($data);
919 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
921 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
923 $item = Item::selectFirst([], ['uri' => $object_id]);
924 if (!DBA::isResult($item)) {
925 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
928 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
929 $data = ActivityPub\Transmitter::createNote($item);
930 $object = JsonLD::compact($data);
933 $id = JsonLD::fetchElement($object, '@id');
935 Logger::info('Empty id');
939 if ($id != $object_id) {
940 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
944 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
947 $type = JsonLD::fetchElement($object, '@type');
949 Logger::info('Empty type');
953 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
954 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
955 $object_data = self::processObject($object);
958 $object_data['raw'] = json_encode($data);
963 if ($type == 'as:Announce') {
964 $object_id = JsonLD::fetchElement($object, 'object', '@id');
965 if (empty($object_id) || !is_string($object_id)) {
968 return self::fetchObject($object_id, [], false, $uid);
971 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
976 * Convert tags from JSON-LD format into a simplified format
978 * @param array $tags Tags in JSON-LD format
980 * @return array with tags in a simplified format
982 public static function processTags(array $tags)
986 foreach ($tags as $tag) {
991 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
992 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
993 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
995 if (empty($element['type'])) {
999 if (empty($element['href'])) {
1000 $element['href'] = $element['name'];
1003 $taglist[] = $element;
1009 * Convert emojis from JSON-LD format into a simplified format
1011 * @param array $emojis
1012 * @return array with emojis in a simplified format
1014 private static function processEmojis(array $emojis)
1018 foreach ($emojis as $emoji) {
1019 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1023 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1024 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1027 $emojilist[] = $element;
1034 * Convert attachments from JSON-LD format into a simplified format
1036 * @param array $attachments Attachments in JSON-LD format
1038 * @return array Attachments in a simplified format
1040 private static function processAttachments(array $attachments)
1044 // Removes empty values
1045 $attachments = array_filter($attachments);
1047 foreach ($attachments as $attachment) {
1048 switch (JsonLD::fetchElement($attachment, '@type')) {
1053 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1054 foreach ($urls as $url) {
1055 // Single scalar URL case
1056 if (is_string($url)) {
1061 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1062 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1063 if (Strings::startsWith($mediaType, 'image')) {
1072 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1073 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1075 'image' => $pageImage,
1080 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1081 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1082 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1083 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1087 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1088 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1089 $imagePreviewUrl = null;
1091 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1092 $imageVariants = [];
1093 $previewVariants = [];
1094 foreach ($urls as $url) {
1095 // Scalar URL, no discrimination possible
1096 if (is_string($url)) {
1097 $imageFullUrl = $url;
1101 // Not sure what to do with a different Link media type than the base Image, we skip
1102 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1106 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1108 // Default URL choice if no discriminating width is provided
1109 $imageFullUrl = $href ?? $imageFullUrl;
1111 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1113 if ($href && $width) {
1114 $imageVariants[$width] = $href;
1115 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1116 $previewVariants[abs(632 - $width)] = $href;
1120 if ($imageVariants) {
1121 // Taking the maximum size image
1122 ksort($imageVariants);
1123 $imageFullUrl = array_pop($imageVariants);
1125 // Taking the minimum number distance to the target distance
1126 ksort($previewVariants);
1127 $imagePreviewUrl = array_shift($previewVariants);
1130 unset($imageVariants);
1131 unset($previewVariants);
1135 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1136 'mediaType' => $mediaType,
1137 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1138 'url' => $imageFullUrl,
1139 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1144 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1145 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1146 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1147 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1156 * Fetch the original source or content with the "language" Markdown or HTML
1158 * @param array $object
1159 * @param array $object_data
1162 * @throws \Exception
1164 private static function getSource($object, $object_data)
1166 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1167 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1168 if (!empty($object_data['source'])) {
1169 return $object_data;
1172 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1173 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1174 if (!empty($object_data['source'])) {
1175 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1176 return $object_data;
1179 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1180 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1181 if (!empty($object_data['source'])) {
1182 $object_data['source'] = HTML::toBBCode($object_data['source']);
1183 return $object_data;
1186 return $object_data;
1190 * Check if the "as:url" element is an array with multiple links
1191 * This is the case with audio and video posts.
1192 * Then the links are added as attachments
1194 * @param array $object The raw object
1195 * @param array $object_data The parsed object data for later processing
1196 * @return array the object data
1198 private static function processAttachmentUrls(array $object, array $object_data) {
1199 // Check if this is some url with multiple links
1200 if (empty($object['as:url'])) {
1201 return $object_data;
1204 $urls = $object['as:url'];
1205 $keys = array_keys($urls);
1206 if (!is_numeric(array_pop($keys))) {
1207 return $object_data;
1212 foreach ($urls as $url) {
1213 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1217 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1222 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1223 if (empty($mediatype)) {
1227 if ($mediatype == 'text/html') {
1228 $object_data['alternate-url'] = $href;
1231 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1233 if ($filetype == 'audio') {
1234 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1235 } elseif ($filetype == 'video') {
1236 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1237 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1239 // We save bandwidth by using a moderate height (alt least 480 pixel height)
1240 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1241 if (!empty($attachments[$filetype]['height']) &&
1242 ($height > $attachments[$filetype]['height']) && ($attachments[$filetype]['height'] >= 480)) {
1246 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1247 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1248 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1250 // For Torrent links we always store the highest resolution
1251 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1255 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1259 foreach ($attachments as $type => $attachment) {
1260 $object_data['attachments'][] = ['type' => $type,
1261 'mediaType' => $attachment['type'],
1262 'height' => $attachment['height'],
1263 'size' => $attachment['size'],
1265 'url' => $attachment['url']];
1267 return $object_data;
1271 * Fetches data from the object part of an activity
1273 * @param array $object
1276 * @throws \Exception
1278 private static function processObject($object)
1280 if (!JsonLD::fetchElement($object, '@id')) {
1285 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1286 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1287 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1289 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1290 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1291 $object_data['reply-to-id'] = $object_data['id'];
1293 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1294 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1295 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1296 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1297 $object_data['reply-to-id'] = $replyToId;
1301 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1302 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1304 if (empty($object_data['updated'])) {
1305 $object_data['updated'] = $object_data['published'];
1308 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1309 $object_data['published'] = $object_data['updated'];
1312 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1313 if (empty($actor)) {
1314 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1317 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1318 $location = JsonLD::fetchElement($location, 'location', '@value');
1320 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1321 // down to HTML and then finally format to plaintext.
1322 $location = Markdown::convert($location);
1323 $location = BBCode::convert($location);
1324 $location = HTML::toPlaintext($location);
1327 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1328 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1329 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1330 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1331 $object_data['actor'] = $object_data['author'] = $actor;
1332 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1333 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1334 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1335 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1336 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1337 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1338 $object_data = self::getSource($object, $object_data);
1339 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1340 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1341 $object_data['location'] = $location;
1342 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1343 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1344 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1345 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1346 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1347 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1348 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1349 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1350 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1351 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1353 // Special treatment for Hubzilla links
1354 if (is_array($object_data['alternate-url'])) {
1355 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1357 if (!is_string($object_data['alternate-url'])) {
1358 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1362 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1363 $object_data = self::processAttachmentUrls($object, $object_data);
1366 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1367 $receivers = $reception_types = [];
1368 foreach ($receiverdata as $key => $data) {
1369 $receivers[$key] = $data['uid'];
1370 $reception_types[$data['uid']] = $data['type'] ?? 0;
1373 $object_data['receiver'] = $receivers;
1374 $object_data['reception_type'] = $reception_types;
1376 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1377 unset($object_data['receiver'][-1]);
1378 unset($object_data['reception_type'][-1]);
1380 // Common object data:
1383 // @context, type, actor, signature, mediaType, duration, replies, icon
1385 // Also missing: (Defined in the standard, but currently unused)
1386 // audience, preview, endTime, startTime, image
1391 // contentMap, announcement_count, announcements, context_id, likes, like_count
1392 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1397 // category, licence, language, commentsEnabled
1400 // views, waitTranscoding, state, support, subtitleLanguage
1401 // likes, dislikes, shares, comments
1403 return $object_data;