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\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', ['actor' => $actor]);
105 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
106 self::processRelayPost($ldactivity, $actor);
109 APContact::unmarkForArchival($apcontact);
112 $http_signer = HTTPSignature::getSigner($body, $header);
113 if (empty($http_signer)) {
114 Logger::warning('Invalid HTTP signature, message will be discarded.');
117 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
120 $signer = [$http_signer];
122 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
124 if (LDSignature::isSigned($activity)) {
125 $ld_signer = LDSignature::getSigner($activity);
126 if (empty($ld_signer)) {
127 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
128 } elseif ($ld_signer != $http_signer) {
129 $signer[] = $ld_signer;
131 if (!empty($ld_signer && ($actor == $http_signer))) {
132 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
133 $trust_source = true;
134 } elseif (!empty($ld_signer)) {
135 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
136 $trust_source = true;
137 } elseif ($actor == $http_signer) {
138 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
139 $trust_source = true;
141 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
142 $trust_source = false;
144 } elseif ($actor == $http_signer) {
145 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
146 $trust_source = true;
148 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
149 $trust_source = false;
152 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
156 * Process incoming posts from relays
158 * @param array $activity
159 * @param string $actor
162 private static function processRelayPost(array $activity, string $actor)
164 $type = JsonLD::fetchElement($activity, '@type');
166 Logger::info('Empty type', ['activity' => $activity]);
170 if ($type != 'as:Announce') {
171 Logger::info('Not an announcement', ['activity' => $activity]);
175 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
176 if (empty($object_id)) {
177 Logger::info('No object id found', ['activity' => $activity]);
181 $contact = Contact::getByURL($actor);
182 if (empty($contact)) {
183 Logger::info('Relay contact not found', ['actor' => $actor]);
187 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
188 Logger::notice('Relay is no sharer', ['actor' => $actor]);
192 Logger::info('Got relayed message id', ['id' => $object_id]);
194 $item_id = Item::searchByLink($object_id);
196 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
200 $id = Processor::fetchMissingActivity($object_id, [], $actor);
202 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
206 $item_id = Item::searchByLink($object_id);
208 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
210 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
215 * Fetches the object type for a given object id
217 * @param array $activity
218 * @param string $object_id Object ID of the the provided object
219 * @param integer $uid User ID
221 * @return string with object type
222 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
223 * @throws \ImagickException
225 private static function fetchObjectType($activity, $object_id, $uid = 0)
227 if (!empty($activity['as:object'])) {
228 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
229 if (!empty($object_type)) {
234 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
235 // We just assume "note" since it doesn't make a difference for the further processing
239 $profile = APContact::getByURL($object_id);
240 if (!empty($profile['type'])) {
241 APContact::unmarkForArchival($profile);
242 return 'as:' . $profile['type'];
245 $data = ActivityPub::fetchContent($object_id, $uid);
247 $object = JsonLD::compact($data);
248 $type = JsonLD::fetchElement($object, '@type');
258 * Prepare the object array
260 * @param array $activity Array with activity data
261 * @param integer $uid User ID
262 * @param boolean $push Message had been pushed to our system
263 * @param boolean $trust_source Do we trust the source?
265 * @return array with object data
266 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
267 * @throws \ImagickException
269 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
271 $id = JsonLD::fetchElement($activity, '@id');
272 if (!empty($id) && !$trust_source) {
273 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
274 if (!empty($fetched_activity)) {
275 $object = JsonLD::compact($fetched_activity);
276 $fetched_id = JsonLD::fetchElement($object, '@id');
277 if ($fetched_id == $id) {
278 Logger::info('Activity had been fetched successfully', ['id' => $id]);
279 $trust_source = true;
282 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
285 Logger::info('Activity could not been fetched', ['id' => $id]);
289 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
291 Logger::info('Empty actor', ['activity' => $activity]);
295 $type = JsonLD::fetchElement($activity, '@type');
297 // Fetch all receivers from to, cc, bto and bcc
298 $receiverdata = self::getReceivers($activity, $actor);
299 $receivers = $reception_types = [];
300 foreach ($receiverdata as $key => $data) {
301 $receivers[$key] = $data['uid'];
302 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
305 // When it is a delivery to a personal inbox we add that user to the receivers
307 $additional = [$uid => $uid];
308 $receivers = array_replace($receivers, $additional);
309 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]))) {
310 $reception_types[$uid] = self::TARGET_BCC;
313 // We possibly need some user to fetch private content,
314 // so we fetch the first out ot the list.
315 $uid = self::getFirstUserFromReceivers($receivers);
318 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
319 if (empty($object_id)) {
320 Logger::log('No object found', Logger::DEBUG);
324 if (!is_string($object_id)) {
325 Logger::info('Invalid object id', ['object' => $object_id]);
329 $object_type = self::fetchObjectType($activity, $object_id, $uid);
331 // Fetch the content only on activities where this matters
332 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
333 // Always fetch on "Announce"
334 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
335 if (empty($object_data)) {
336 Logger::log("Object data couldn't be processed", Logger::DEBUG);
340 $object_data['object_id'] = $object_id;
342 if ($type == 'as:Announce') {
343 $object_data['push'] = false;
345 $object_data['push'] = $push;
348 // Test if it is an answer to a mail
349 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
350 $object_data['directmessage'] = true;
352 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
354 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
355 // Create a mostly empty array out of the activity data (instead of the object).
356 // This way we later don't have to check for the existence of ech individual array element.
357 $object_data = self::processObject($activity);
358 $object_data['name'] = $type;
359 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
360 $object_data['object_id'] = $object_id;
361 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
362 $object_data['push'] = $push;
363 } elseif (in_array($type, ['as:Add'])) {
365 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
366 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
367 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
368 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
369 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
370 $object_data['push'] = $push;
373 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
374 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
375 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
376 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
377 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
378 $object_data['push'] = $push;
380 // An Undo is done on the object of an object, so we need that type as well
381 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
382 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
386 $object_data = self::addActivityFields($object_data, $activity);
388 if (empty($object_data['object_type'])) {
389 $object_data['object_type'] = $object_type;
392 $object_data['type'] = $type;
393 $object_data['actor'] = $actor;
394 $object_data['item_receiver'] = $receivers;
395 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
396 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
398 $author = $object_data['author'] ?? $actor;
399 if (!empty($author) && !empty($object_data['id'])) {
400 $author_host = parse_url($author, PHP_URL_HOST);
401 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
402 if ($author_host == $id_host) {
403 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
405 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
406 $trust_source = false;
410 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
416 * Fetches the first user id from the receiver array
418 * @param array $receivers Array with receivers
419 * @return integer user id;
421 public static function getFirstUserFromReceivers($receivers)
423 foreach ($receivers as $receiver) {
424 if (!empty($receiver)) {
432 * Processes the activity object
434 * @param array $activity Array with activity data
435 * @param string $body
436 * @param integer $uid User ID
437 * @param boolean $trust_source Do we trust the source?
438 * @param boolean $push Message had been pushed to our system
441 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
443 $type = JsonLD::fetchElement($activity, '@type');
445 Logger::info('Empty type', ['activity' => $activity]);
449 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
450 Logger::info('Empty object', ['activity' => $activity]);
454 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
456 Logger::info('Empty actor', ['activity' => $activity]);
460 if (is_array($activity['as:object'])) {
461 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
466 // Test the provided signatures against the actor and "attributedTo"
468 if (!empty($attributed_to) && !empty($actor)) {
469 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
471 $trust_source = in_array($actor, $signer);
475 // $trust_source is called by reference and is set to true if the content was retrieved successfully
476 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
477 if (empty($object_data)) {
478 Logger::info('No object data found', ['activity' => $activity]);
482 if (!$trust_source) {
483 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
487 if (!empty($body) && empty($object_data['raw'])) {
488 $object_data['raw'] = $body;
491 // Internal flag for thread completion. See Processor.php
492 if (!empty($activity['thread-completion'])) {
493 $object_data['thread-completion'] = $activity['thread-completion'];
496 // Internal flag for posts that arrived via relay
497 if (!empty($activity['from-relay'])) {
498 $object_data['from-relay'] = $activity['from-relay'];
503 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
504 $item = ActivityPub\Processor::createItem($object_data);
505 ActivityPub\Processor::postItem($object_data, $item);
510 if ($object_data['object_type'] == 'as:tag') {
511 ActivityPub\Processor::addTag($object_data);
516 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
517 $object_data['thread-completion'] = Contact::getIdForURL($actor);
519 $item = ActivityPub\Processor::createItem($object_data);
524 $item['post-type'] = Item::PT_ANNOUNCEMENT;
525 ActivityPub\Processor::postItem($object_data, $item);
527 $announce_object_data = self::processObject($activity);
528 $announce_object_data['name'] = $type;
529 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
530 $announce_object_data['object_id'] = $object_data['object_id'];
531 $announce_object_data['object_type'] = $object_data['object_type'];
532 $announce_object_data['push'] = $push;
535 $announce_object_data['raw'] = $body;
538 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
543 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
544 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
549 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
550 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
554 case 'as:TentativeAccept':
555 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
556 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
561 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
562 ActivityPub\Processor::updateItem($object_data);
563 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
564 ActivityPub\Processor::updatePerson($object_data);
569 if ($object_data['object_type'] == 'as:Tombstone') {
570 ActivityPub\Processor::deleteItem($object_data);
571 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
572 ActivityPub\Processor::deletePerson($object_data);
577 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
578 ActivityPub\Processor::followUser($object_data);
579 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
580 $object_data['reply-to-id'] = $object_data['object_id'];
581 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
586 if ($object_data['object_type'] == 'as:Follow') {
587 ActivityPub\Processor::acceptFollowUser($object_data);
588 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
589 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
594 if ($object_data['object_type'] == 'as:Follow') {
595 ActivityPub\Processor::rejectFollowUser($object_data);
596 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
597 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
602 if (($object_data['object_type'] == 'as:Follow') &&
603 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
604 ActivityPub\Processor::undoFollowUser($object_data);
605 } elseif (($object_data['object_type'] == 'as:Accept') &&
606 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
607 ActivityPub\Processor::rejectFollowUser($object_data);
608 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
609 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
610 ActivityPub\Processor::undoActivity($object_data);
615 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
621 * Fetch the receiver list from an activity array
623 * @param array $activity
624 * @param string $actor
626 * @param boolean $fetch_unlisted
628 * @return array with receivers (user id)
631 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
633 $reply = $receivers = [];
635 // When it is an answer, we inherite the receivers from the parent
636 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
637 if (!empty($replyto)) {
640 // Fix possibly wrong item URI (could be an answer to a plink uri)
641 $fixedReplyTo = Item::getURIByLink($replyto);
642 if (!empty($fixedReplyTo)) {
643 $reply[] = $fixedReplyTo;
647 // Fetch all posts that refer to the object id
648 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
649 if (!empty($object_id)) {
650 $reply[] = $object_id;
653 if (!empty($reply)) {
654 $parents = Post::select(['uid'], ['uri' => $reply]);
655 while ($parent = Post::fetch($parents)) {
656 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
658 DBA::close($parents);
661 if (!empty($actor)) {
662 $profile = APContact::getByURL($actor);
663 $followers = $profile['followers'] ?? '';
665 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
667 Logger::info('Empty actor', ['activity' => $activity]);
671 // We have to prevent false follower assumptions upon thread completions
672 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
674 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
675 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
676 if (empty($receiver_list)) {
680 foreach ($receiver_list as $receiver) {
681 if ($receiver == self::PUBLIC_COLLECTION) {
682 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
685 // Add receiver "-1" for unlisted posts
686 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
687 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
690 // Fetch the receivers for the public and the followers collection
691 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
692 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
696 // Fetching all directly addressed receivers
697 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
698 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
699 if (!DBA::isResult($contact)) {
703 // Check if the potential receiver is following the actor
704 // Exception: The receiver is targetted via "to" or this is a comment
705 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
706 $networks = Protocol::FEDERATED;
707 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
708 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
710 // Forum posts are only accepted from forum contacts
711 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
712 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
715 if (!DBA::exists('contact', $condition)) {
720 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
721 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
724 $type = self::TARGET_TO;
727 $type = self::TARGET_CC;
730 $type = self::TARGET_BTO;
733 $type = self::TARGET_BCC;
737 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
742 self::switchContacts($receivers, $actor);
748 * Fetch the receiver list of a given actor
750 * @param string $actor
752 * @param array $receivers
753 * @param integer $target_type
755 * @return array with receivers (user id)
758 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
760 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
761 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
763 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($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);
772 // The queries are split because of performance issues
773 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
774 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
775 while ($contact = DBA::fetch($contacts)) {
776 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
777 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
780 DBA::close($contacts);
785 * Tests if the contact is a valid receiver for this actor
787 * @param array $contact
788 * @param string $actor
791 * @return bool with receivers (user id)
794 private static function isValidReceiverForActor($contact, $tags)
796 // Are we following the contact? Then this is a valid receiver
797 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
801 // When the possible receiver isn't a community, then it is no valid receiver
802 $owner = User::getOwnerDataById($contact['uid']);
803 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
807 // Is the community account tagged?
808 foreach ($tags as $tag) {
809 if ($tag['type'] != 'Mention') {
813 if (Strings::compareLink($tag['href'], $owner['url'])) {
822 * Switches existing contacts to ActivityPub
824 * @param integer $cid Contact ID
825 * @param integer $uid User ID
826 * @param string $url Profile URL
827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
828 * @throws \ImagickException
830 public static function switchContact($cid, $uid, $url)
832 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
833 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
837 if (Contact::updateFromProbe($cid)) {
838 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
841 // Send a new follow request to be sure that the connection still exists
842 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
843 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
844 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
853 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
854 * @throws \ImagickException
856 private static function switchContacts($receivers, $actor)
862 foreach ($receivers as $receiver) {
863 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
864 if (DBA::isResult($contact)) {
865 self::switchContact($contact['id'], $receiver['uid'], $actor);
868 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
869 if (DBA::isResult($contact)) {
870 self::switchContact($contact['id'], $receiver['uid'], $actor);
878 * @param $object_data
879 * @param array $activity
883 private static function addActivityFields($object_data, $activity)
885 if (!empty($activity['published']) && empty($object_data['published'])) {
886 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
889 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
890 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
893 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
894 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
896 if (!empty($object_data['object_id'])) {
897 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
898 $objectId = Item::getURIByLink($object_data['object_id']);
899 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
900 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
901 $object_data['object_id'] = $objectId;
909 * Fetches the object data from external ressources if needed
911 * @param string $object_id Object ID of the the provided object
912 * @param array $object The provided object array
913 * @param boolean $trust_source Do we trust the provided object?
914 * @param integer $uid User ID for the signature that we use to fetch data
916 * @return array|false with trusted and valid object data
917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
918 * @throws \ImagickException
920 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
922 // By fetching the type we check if the object is complete.
923 $type = JsonLD::fetchElement($object, '@type');
925 if (!$trust_source || empty($type)) {
926 $data = ActivityPub::fetchContent($object_id, $uid);
928 $object = JsonLD::compact($data);
929 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
931 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
933 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
934 if (!DBA::isResult($item)) {
935 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
938 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
939 $data = ActivityPub\Transmitter::createNote($item);
940 $object = JsonLD::compact($data);
943 $id = JsonLD::fetchElement($object, '@id');
945 Logger::info('Empty id');
949 if ($id != $object_id) {
950 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
954 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
957 $type = JsonLD::fetchElement($object, '@type');
959 Logger::info('Empty type');
963 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
964 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
965 $object_data = self::processObject($object);
968 $object_data['raw'] = json_encode($data);
973 if ($type == 'as:Announce') {
974 $object_id = JsonLD::fetchElement($object, 'object', '@id');
975 if (empty($object_id) || !is_string($object_id)) {
978 return self::fetchObject($object_id, [], false, $uid);
981 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
986 * Converts the language element (Used by Peertube)
988 * @param array $languages
989 * @return array Languages
991 public static function processLanguages(array $languages)
993 if (empty($languages)) {
999 foreach ($languages as $language) {
1000 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1001 $language_list[$language['_:identifier']] = $language['as:name'];
1004 return $language_list;
1008 * Convert tags from JSON-LD format into a simplified format
1010 * @param array $tags Tags in JSON-LD format
1012 * @return array with tags in a simplified format
1014 public static function processTags(array $tags)
1018 foreach ($tags as $tag) {
1023 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1024 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1025 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1027 if (empty($element['type'])) {
1031 if (empty($element['href'])) {
1032 $element['href'] = $element['name'];
1035 $taglist[] = $element;
1041 * Convert emojis from JSON-LD format into a simplified format
1043 * @param array $emojis
1044 * @return array with emojis in a simplified format
1046 private static function processEmojis(array $emojis)
1050 foreach ($emojis as $emoji) {
1051 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1055 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1056 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1059 $emojilist[] = $element;
1066 * Convert attachments from JSON-LD format into a simplified format
1068 * @param array $attachments Attachments in JSON-LD format
1070 * @return array Attachments in a simplified format
1072 private static function processAttachments(array $attachments)
1076 // Removes empty values
1077 $attachments = array_filter($attachments);
1079 foreach ($attachments as $attachment) {
1080 switch (JsonLD::fetchElement($attachment, '@type')) {
1085 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1086 foreach ($urls as $url) {
1087 // Single scalar URL case
1088 if (is_string($url)) {
1093 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1094 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1095 if (Strings::startsWith($mediaType, 'image')) {
1104 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1105 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1107 'image' => $pageImage,
1112 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1113 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1114 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1115 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1119 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1120 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1121 $imagePreviewUrl = null;
1123 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1124 $imageVariants = [];
1125 $previewVariants = [];
1126 foreach ($urls as $url) {
1127 // Scalar URL, no discrimination possible
1128 if (is_string($url)) {
1129 $imageFullUrl = $url;
1133 // Not sure what to do with a different Link media type than the base Image, we skip
1134 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1138 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1140 // Default URL choice if no discriminating width is provided
1141 $imageFullUrl = $href ?? $imageFullUrl;
1143 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1145 if ($href && $width) {
1146 $imageVariants[$width] = $href;
1147 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1148 $previewVariants[abs(632 - $width)] = $href;
1152 if ($imageVariants) {
1153 // Taking the maximum size image
1154 ksort($imageVariants);
1155 $imageFullUrl = array_pop($imageVariants);
1157 // Taking the minimum number distance to the target distance
1158 ksort($previewVariants);
1159 $imagePreviewUrl = array_shift($previewVariants);
1162 unset($imageVariants);
1163 unset($previewVariants);
1167 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1168 'mediaType' => $mediaType,
1169 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1170 'url' => $imageFullUrl,
1171 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1176 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1177 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1178 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1179 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1188 * Fetch the original source or content with the "language" Markdown or HTML
1190 * @param array $object
1191 * @param array $object_data
1194 * @throws \Exception
1196 private static function getSource($object, $object_data)
1198 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1199 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1200 if (!empty($object_data['source'])) {
1201 return $object_data;
1204 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1205 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1206 if (!empty($object_data['source'])) {
1207 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1208 return $object_data;
1211 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1212 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1213 if (!empty($object_data['source'])) {
1214 $object_data['source'] = HTML::toBBCode($object_data['source']);
1215 return $object_data;
1218 return $object_data;
1222 * Check if the "as:url" element is an array with multiple links
1223 * This is the case with audio and video posts.
1224 * Then the links are added as attachments
1226 * @param array $object The raw object
1227 * @param array $object_data The parsed object data for later processing
1228 * @return array the object data
1230 private static function processAttachmentUrls(array $object, array $object_data) {
1231 // Check if this is some url with multiple links
1232 if (empty($object['as:url'])) {
1233 return $object_data;
1236 $urls = $object['as:url'];
1237 $keys = array_keys($urls);
1238 if (!is_numeric(array_pop($keys))) {
1239 return $object_data;
1244 foreach ($urls as $url) {
1245 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1249 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1254 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1255 if (empty($mediatype)) {
1259 if ($mediatype == 'text/html') {
1260 $object_data['alternate-url'] = $href;
1263 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1265 if ($filetype == 'audio') {
1266 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1267 } elseif ($filetype == 'video') {
1268 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1269 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1271 // We save bandwidth by using a moderate height (alt least 480 pixel height)
1272 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1273 if (!empty($attachments[$filetype]['height']) &&
1274 ($height > $attachments[$filetype]['height']) && ($attachments[$filetype]['height'] >= 480)) {
1278 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1279 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1280 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1282 // For Torrent links we always store the highest resolution
1283 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1287 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1291 foreach ($attachments as $type => $attachment) {
1292 $object_data['attachments'][] = ['type' => $type,
1293 'mediaType' => $attachment['type'],
1294 'height' => $attachment['height'],
1295 'size' => $attachment['size'],
1297 'url' => $attachment['url']];
1299 return $object_data;
1303 * Fetches data from the object part of an activity
1305 * @param array $object
1308 * @throws \Exception
1310 private static function processObject($object)
1312 if (!JsonLD::fetchElement($object, '@id')) {
1317 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1318 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1319 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1321 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1322 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1323 $object_data['reply-to-id'] = $object_data['id'];
1325 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1326 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1327 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1328 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1329 $object_data['reply-to-id'] = $replyToId;
1333 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1334 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1336 if (empty($object_data['updated'])) {
1337 $object_data['updated'] = $object_data['published'];
1340 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1341 $object_data['published'] = $object_data['updated'];
1344 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1345 if (empty($actor)) {
1346 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1349 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1350 $location = JsonLD::fetchElement($location, 'location', '@value');
1352 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1353 // down to HTML and then finally format to plaintext.
1354 $location = Markdown::convert($location);
1355 $location = BBCode::convert($location);
1356 $location = HTML::toPlaintext($location);
1359 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1360 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1361 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1362 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1363 $object_data['actor'] = $object_data['author'] = $actor;
1364 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1365 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1366 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1367 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1368 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1369 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1370 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1371 $object_data = self::getSource($object, $object_data);
1372 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1373 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1374 $object_data['location'] = $location;
1375 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1376 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1377 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1378 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1379 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1380 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1381 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1382 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1383 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1384 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1385 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1387 // Special treatment for Hubzilla links
1388 if (is_array($object_data['alternate-url'])) {
1389 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1391 if (!is_string($object_data['alternate-url'])) {
1392 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1396 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1397 $object_data = self::processAttachmentUrls($object, $object_data);
1400 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1401 $receivers = $reception_types = [];
1402 foreach ($receiverdata as $key => $data) {
1403 $receivers[$key] = $data['uid'];
1404 $reception_types[$data['uid']] = $data['type'] ?? 0;
1407 $object_data['receiver'] = $receivers;
1408 $object_data['reception_type'] = $reception_types;
1410 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1411 unset($object_data['receiver'][-1]);
1412 unset($object_data['reception_type'][-1]);
1414 // Common object data:
1417 // @context, type, actor, signature, mediaType, duration, replies, icon
1419 // Also missing: (Defined in the standard, but currently unused)
1420 // audience, preview, endTime, startTime, image
1425 // contentMap, announcement_count, announcements, context_id, likes, like_count
1426 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1431 // category, licence, language, commentsEnabled
1434 // views, waitTranscoding, state, support, subtitleLanguage
1435 // likes, dislikes, shares, comments
1437 return $object_data;