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 - message is discarded', ['actor' => $actor]);
106 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
107 self::processRelayPost($ldactivity, $actor);
110 APContact::unmarkForArchival($apcontact);
113 $http_signer = HTTPSignature::getSigner($body, $header);
114 if (empty($http_signer)) {
115 Logger::warning('Invalid HTTP signature, message will be discarded.');
118 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
121 $signer = [$http_signer];
123 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
125 if (LDSignature::isSigned($activity)) {
126 $ld_signer = LDSignature::getSigner($activity);
127 if (empty($ld_signer)) {
128 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
129 } elseif ($ld_signer != $http_signer) {
130 $signer[] = $ld_signer;
132 if (!empty($ld_signer && ($actor == $http_signer))) {
133 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
134 $trust_source = true;
135 } elseif (!empty($ld_signer)) {
136 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
137 $trust_source = true;
138 } elseif ($actor == $http_signer) {
139 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
140 $trust_source = true;
142 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
143 $trust_source = false;
145 } elseif ($actor == $http_signer) {
146 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
147 $trust_source = true;
149 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
150 $trust_source = false;
153 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
157 * Process incoming posts from relays
159 * @param array $activity
160 * @param string $actor
163 private static function processRelayPost(array $activity, string $actor)
165 $type = JsonLD::fetchElement($activity, '@type');
167 Logger::info('Empty type', ['activity' => $activity]);
171 if ($type != 'as:Announce') {
172 Logger::info('Not an announcement', ['activity' => $activity]);
176 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
177 if (empty($object_id)) {
178 Logger::info('No object id found', ['activity' => $activity]);
182 $contact = Contact::getByURL($actor);
183 if (empty($contact)) {
184 Logger::info('Relay contact not found', ['actor' => $actor]);
188 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
189 Logger::notice('Relay is no sharer', ['actor' => $actor]);
193 Logger::info('Got relayed message id', ['id' => $object_id]);
195 $item_id = Item::searchByLink($object_id);
197 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
201 $id = Processor::fetchMissingActivity($object_id, [], $actor);
203 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
207 $item_id = Item::searchByLink($object_id);
209 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
211 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
216 * Fetches the object type for a given object id
218 * @param array $activity
219 * @param string $object_id Object ID of the the provided object
220 * @param integer $uid User ID
222 * @return string with object type
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224 * @throws \ImagickException
226 private static function fetchObjectType($activity, $object_id, $uid = 0)
228 if (!empty($activity['as:object'])) {
229 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
230 if (!empty($object_type)) {
235 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
236 // We just assume "note" since it doesn't make a difference for the further processing
240 $profile = APContact::getByURL($object_id);
241 if (!empty($profile['type'])) {
242 APContact::unmarkForArchival($profile);
243 return 'as:' . $profile['type'];
246 $data = ActivityPub::fetchContent($object_id, $uid);
248 $object = JsonLD::compact($data);
249 $type = JsonLD::fetchElement($object, '@type');
259 * Prepare the object array
261 * @param array $activity Array with activity data
262 * @param integer $uid User ID
263 * @param boolean $push Message had been pushed to our system
264 * @param boolean $trust_source Do we trust the source?
266 * @return array with object data
267 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268 * @throws \ImagickException
270 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
272 $id = JsonLD::fetchElement($activity, '@id');
273 if (!empty($id) && !$trust_source) {
274 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
275 if (!empty($fetched_activity)) {
276 $object = JsonLD::compact($fetched_activity);
277 $fetched_id = JsonLD::fetchElement($object, '@id');
278 if ($fetched_id == $id) {
279 Logger::info('Activity had been fetched successfully', ['id' => $id]);
280 $trust_source = true;
283 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
286 Logger::info('Activity could not been fetched', ['id' => $id]);
290 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
292 Logger::info('Empty actor', ['activity' => $activity]);
296 $type = JsonLD::fetchElement($activity, '@type');
298 // Fetch all receivers from to, cc, bto and bcc
299 $receiverdata = self::getReceivers($activity, $actor);
300 $receivers = $reception_types = [];
301 foreach ($receiverdata as $key => $data) {
302 $receivers[$key] = $data['uid'];
303 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
306 // When it is a delivery to a personal inbox we add that user to the receivers
308 $additional = [$uid => $uid];
309 $receivers = array_replace($receivers, $additional);
310 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]))) {
311 $reception_types[$uid] = self::TARGET_BCC;
314 // We possibly need some user to fetch private content,
315 // so we fetch the first out ot the list.
316 $uid = self::getFirstUserFromReceivers($receivers);
319 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
320 if (empty($object_id)) {
321 Logger::log('No object found', Logger::DEBUG);
325 if (!is_string($object_id)) {
326 Logger::info('Invalid object id', ['object' => $object_id]);
330 $object_type = self::fetchObjectType($activity, $object_id, $uid);
332 // Fetch the content only on activities where this matters
333 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
334 // Always fetch on "Announce"
335 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
336 if (empty($object_data)) {
337 Logger::log("Object data couldn't be processed", Logger::DEBUG);
341 $object_data['object_id'] = $object_id;
343 if ($type == 'as:Announce') {
344 $object_data['push'] = false;
346 $object_data['push'] = $push;
349 // Test if it is an answer to a mail
350 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
351 $object_data['directmessage'] = true;
353 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
355 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
356 // Create a mostly empty array out of the activity data (instead of the object).
357 // This way we later don't have to check for the existence of ech individual array element.
358 $object_data = self::processObject($activity);
359 $object_data['name'] = $type;
360 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
361 $object_data['object_id'] = $object_id;
362 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
363 $object_data['push'] = $push;
364 } elseif (in_array($type, ['as:Add'])) {
366 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
367 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
368 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
369 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
370 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
371 $object_data['push'] = $push;
374 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
375 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
376 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
377 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
378 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
379 $object_data['push'] = $push;
381 // An Undo is done on the object of an object, so we need that type as well
382 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
383 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
387 $object_data = self::addActivityFields($object_data, $activity);
389 if (empty($object_data['object_type'])) {
390 $object_data['object_type'] = $object_type;
393 $object_data['type'] = $type;
394 $object_data['actor'] = $actor;
395 $object_data['item_receiver'] = $receivers;
396 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
397 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
399 $author = $object_data['author'] ?? $actor;
400 if (!empty($author) && !empty($object_data['id'])) {
401 $author_host = parse_url($author, PHP_URL_HOST);
402 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
403 if ($author_host == $id_host) {
404 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
406 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
407 $trust_source = false;
411 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
417 * Fetches the first user id from the receiver array
419 * @param array $receivers Array with receivers
420 * @return integer user id;
422 public static function getFirstUserFromReceivers($receivers)
424 foreach ($receivers as $receiver) {
425 if (!empty($receiver)) {
433 * Processes the activity object
435 * @param array $activity Array with activity data
436 * @param string $body
437 * @param integer $uid User ID
438 * @param boolean $trust_source Do we trust the source?
439 * @param boolean $push Message had been pushed to our system
442 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
444 $type = JsonLD::fetchElement($activity, '@type');
446 Logger::info('Empty type', ['activity' => $activity]);
450 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
451 Logger::info('Empty object', ['activity' => $activity]);
455 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
457 Logger::info('Empty actor', ['activity' => $activity]);
461 if (is_array($activity['as:object'])) {
462 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
467 // Test the provided signatures against the actor and "attributedTo"
469 if (!empty($attributed_to) && !empty($actor)) {
470 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
472 $trust_source = in_array($actor, $signer);
476 // $trust_source is called by reference and is set to true if the content was retrieved successfully
477 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
478 if (empty($object_data)) {
479 Logger::info('No object data found', ['activity' => $activity]);
483 if (!$trust_source) {
484 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
488 if (!empty($body) && empty($object_data['raw'])) {
489 $object_data['raw'] = $body;
492 // Internal flag for thread completion. See Processor.php
493 if (!empty($activity['thread-completion'])) {
494 $object_data['thread-completion'] = $activity['thread-completion'];
497 // Internal flag for posts that arrived via relay
498 if (!empty($activity['from-relay'])) {
499 $object_data['from-relay'] = $activity['from-relay'];
504 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
505 $item = ActivityPub\Processor::createItem($object_data);
506 ActivityPub\Processor::postItem($object_data, $item);
511 if ($object_data['object_type'] == 'as:tag') {
512 ActivityPub\Processor::addTag($object_data);
517 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
518 $object_data['thread-completion'] = Contact::getIdForURL($actor);
520 $item = ActivityPub\Processor::createItem($object_data);
525 $item['post-type'] = Item::PT_ANNOUNCEMENT;
526 ActivityPub\Processor::postItem($object_data, $item);
528 $announce_object_data = self::processObject($activity);
529 $announce_object_data['name'] = $type;
530 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
531 $announce_object_data['object_id'] = $object_data['object_id'];
532 $announce_object_data['object_type'] = $object_data['object_type'];
533 $announce_object_data['push'] = $push;
536 $announce_object_data['raw'] = $body;
539 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
544 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
545 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
550 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
551 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
555 case 'as:TentativeAccept':
556 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
557 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
562 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
563 ActivityPub\Processor::updateItem($object_data);
564 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
565 ActivityPub\Processor::updatePerson($object_data);
570 if ($object_data['object_type'] == 'as:Tombstone') {
571 ActivityPub\Processor::deleteItem($object_data);
572 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
573 ActivityPub\Processor::deletePerson($object_data);
578 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
579 ActivityPub\Processor::followUser($object_data);
580 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
581 $object_data['reply-to-id'] = $object_data['object_id'];
582 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
587 if ($object_data['object_type'] == 'as:Follow') {
588 ActivityPub\Processor::acceptFollowUser($object_data);
589 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
590 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
595 if ($object_data['object_type'] == 'as:Follow') {
596 ActivityPub\Processor::rejectFollowUser($object_data);
597 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
598 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
603 if (($object_data['object_type'] == 'as:Follow') &&
604 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
605 ActivityPub\Processor::undoFollowUser($object_data);
606 } elseif (($object_data['object_type'] == 'as:Accept') &&
607 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
608 ActivityPub\Processor::rejectFollowUser($object_data);
609 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
610 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
611 ActivityPub\Processor::undoActivity($object_data);
616 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
622 * Fetch the receiver list from an activity array
624 * @param array $activity
625 * @param string $actor
627 * @param boolean $fetch_unlisted
629 * @return array with receivers (user id)
632 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
634 $reply = $receivers = [];
636 // When it is an answer, we inherite the receivers from the parent
637 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
638 if (!empty($replyto)) {
641 // Fix possibly wrong item URI (could be an answer to a plink uri)
642 $fixedReplyTo = Item::getURIByLink($replyto);
643 if (!empty($fixedReplyTo)) {
644 $reply[] = $fixedReplyTo;
648 // Fetch all posts that refer to the object id
649 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
650 if (!empty($object_id)) {
651 $reply[] = $object_id;
654 if (!empty($reply)) {
655 $parents = Post::select(['uid'], ['uri' => $reply]);
656 while ($parent = Post::fetch($parents)) {
657 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
659 DBA::close($parents);
662 if (!empty($actor)) {
663 $profile = APContact::getByURL($actor);
664 $followers = $profile['followers'] ?? '';
666 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
668 Logger::info('Empty actor', ['activity' => $activity]);
672 // We have to prevent false follower assumptions upon thread completions
673 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
675 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
676 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
677 if (empty($receiver_list)) {
681 foreach ($receiver_list as $receiver) {
682 if ($receiver == self::PUBLIC_COLLECTION) {
683 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
686 // Add receiver "-1" for unlisted posts
687 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
688 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
691 // Fetch the receivers for the public and the followers collection
692 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
693 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
697 // Fetching all directly addressed receivers
698 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
699 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
700 if (!DBA::isResult($contact)) {
704 // Check if the potential receiver is following the actor
705 // Exception: The receiver is targetted via "to" or this is a comment
706 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
707 $networks = Protocol::FEDERATED;
708 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
709 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
711 // Forum posts are only accepted from forum contacts
712 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
713 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
716 if (!DBA::exists('contact', $condition)) {
721 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
722 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
725 $type = self::TARGET_TO;
728 $type = self::TARGET_CC;
731 $type = self::TARGET_BTO;
734 $type = self::TARGET_BCC;
738 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
743 self::switchContacts($receivers, $actor);
749 * Fetch the receiver list of a given actor
751 * @param string $actor
753 * @param array $receivers
754 * @param integer $target_type
756 * @return array with receivers (user id)
759 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
761 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
762 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
764 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
765 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
766 while ($contact = DBA::fetch($contacts)) {
767 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
768 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
771 DBA::close($contacts);
773 // The queries are split because of performance issues
774 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
775 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
776 while ($contact = DBA::fetch($contacts)) {
777 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
778 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
781 DBA::close($contacts);
786 * Tests if the contact is a valid receiver for this actor
788 * @param array $contact
789 * @param string $actor
792 * @return bool with receivers (user id)
795 private static function isValidReceiverForActor($contact, $tags)
797 // Are we following the contact? Then this is a valid receiver
798 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
802 // When the possible receiver isn't a community, then it is no valid receiver
803 $owner = User::getOwnerDataById($contact['uid']);
804 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
808 // Is the community account tagged?
809 foreach ($tags as $tag) {
810 if ($tag['type'] != 'Mention') {
814 if (Strings::compareLink($tag['href'], $owner['url'])) {
823 * Switches existing contacts to ActivityPub
825 * @param integer $cid Contact ID
826 * @param integer $uid User ID
827 * @param string $url Profile URL
828 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
829 * @throws \ImagickException
831 public static function switchContact($cid, $uid, $url)
833 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
834 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
838 if (Contact::updateFromProbe($cid)) {
839 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
842 // Send a new follow request to be sure that the connection still exists
843 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
844 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
845 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
854 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
855 * @throws \ImagickException
857 private static function switchContacts($receivers, $actor)
863 foreach ($receivers as $receiver) {
864 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
865 if (DBA::isResult($contact)) {
866 self::switchContact($contact['id'], $receiver['uid'], $actor);
869 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
870 if (DBA::isResult($contact)) {
871 self::switchContact($contact['id'], $receiver['uid'], $actor);
879 * @param $object_data
880 * @param array $activity
884 private static function addActivityFields($object_data, $activity)
886 if (!empty($activity['published']) && empty($object_data['published'])) {
887 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
890 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
891 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
894 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
895 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
897 if (!empty($object_data['object_id'])) {
898 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
899 $objectId = Item::getURIByLink($object_data['object_id']);
900 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
901 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
902 $object_data['object_id'] = $objectId;
910 * Fetches the object data from external ressources if needed
912 * @param string $object_id Object ID of the the provided object
913 * @param array $object The provided object array
914 * @param boolean $trust_source Do we trust the provided object?
915 * @param integer $uid User ID for the signature that we use to fetch data
917 * @return array|false with trusted and valid object data
918 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
919 * @throws \ImagickException
921 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
923 // By fetching the type we check if the object is complete.
924 $type = JsonLD::fetchElement($object, '@type');
926 if (!$trust_source || empty($type)) {
927 $data = ActivityPub::fetchContent($object_id, $uid);
929 $object = JsonLD::compact($data);
930 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
932 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
934 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
935 if (!DBA::isResult($item)) {
936 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
939 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
940 $data = ActivityPub\Transmitter::createNote($item);
941 $object = JsonLD::compact($data);
944 $id = JsonLD::fetchElement($object, '@id');
946 Logger::info('Empty id');
950 if ($id != $object_id) {
951 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
955 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
958 $type = JsonLD::fetchElement($object, '@type');
960 Logger::info('Empty type');
964 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
965 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
966 $object_data = self::processObject($object);
969 $object_data['raw'] = json_encode($data);
974 if ($type == 'as:Announce') {
975 $object_id = JsonLD::fetchElement($object, 'object', '@id');
976 if (empty($object_id) || !is_string($object_id)) {
979 return self::fetchObject($object_id, [], false, $uid);
982 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
987 * Converts the language element (Used by Peertube)
989 * @param array $languages
990 * @return array Languages
992 public static function processLanguages(array $languages)
994 if (empty($languages)) {
1000 foreach ($languages as $language) {
1001 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1002 $language_list[$language['_:identifier']] = $language['as:name'];
1005 return $language_list;
1009 * Convert tags from JSON-LD format into a simplified format
1011 * @param array $tags Tags in JSON-LD format
1013 * @return array with tags in a simplified format
1015 public static function processTags(array $tags)
1019 foreach ($tags as $tag) {
1024 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1025 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1026 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1028 if (empty($element['type'])) {
1032 if (empty($element['href'])) {
1033 $element['href'] = $element['name'];
1036 $taglist[] = $element;
1042 * Convert emojis from JSON-LD format into a simplified format
1044 * @param array $emojis
1045 * @return array with emojis in a simplified format
1047 private static function processEmojis(array $emojis)
1051 foreach ($emojis as $emoji) {
1052 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1056 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1057 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1060 $emojilist[] = $element;
1067 * Convert attachments from JSON-LD format into a simplified format
1069 * @param array $attachments Attachments in JSON-LD format
1071 * @return array Attachments in a simplified format
1073 private static function processAttachments(array $attachments)
1077 // Removes empty values
1078 $attachments = array_filter($attachments);
1080 foreach ($attachments as $attachment) {
1081 switch (JsonLD::fetchElement($attachment, '@type')) {
1086 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1087 foreach ($urls as $url) {
1088 // Single scalar URL case
1089 if (is_string($url)) {
1094 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1095 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1096 if (Strings::startsWith($mediaType, 'image')) {
1105 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1106 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1108 'image' => $pageImage,
1113 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1114 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1115 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1116 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1120 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1121 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1122 $imagePreviewUrl = null;
1124 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1125 $imageVariants = [];
1126 $previewVariants = [];
1127 foreach ($urls as $url) {
1128 // Scalar URL, no discrimination possible
1129 if (is_string($url)) {
1130 $imageFullUrl = $url;
1134 // Not sure what to do with a different Link media type than the base Image, we skip
1135 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1139 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1141 // Default URL choice if no discriminating width is provided
1142 $imageFullUrl = $href ?? $imageFullUrl;
1144 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1146 if ($href && $width) {
1147 $imageVariants[$width] = $href;
1148 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1149 $previewVariants[abs(632 - $width)] = $href;
1153 if ($imageVariants) {
1154 // Taking the maximum size image
1155 ksort($imageVariants);
1156 $imageFullUrl = array_pop($imageVariants);
1158 // Taking the minimum number distance to the target distance
1159 ksort($previewVariants);
1160 $imagePreviewUrl = array_shift($previewVariants);
1163 unset($imageVariants);
1164 unset($previewVariants);
1168 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1169 'mediaType' => $mediaType,
1170 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1171 'url' => $imageFullUrl,
1172 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1177 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1178 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1179 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1180 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1189 * Fetch the original source or content with the "language" Markdown or HTML
1191 * @param array $object
1192 * @param array $object_data
1195 * @throws \Exception
1197 private static function getSource($object, $object_data)
1199 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1200 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1201 if (!empty($object_data['source'])) {
1202 return $object_data;
1205 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1206 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1207 if (!empty($object_data['source'])) {
1208 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1209 return $object_data;
1212 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1213 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1214 if (!empty($object_data['source'])) {
1215 $object_data['source'] = HTML::toBBCode($object_data['source']);
1216 return $object_data;
1219 return $object_data;
1223 * Check if the "as:url" element is an array with multiple links
1224 * This is the case with audio and video posts.
1225 * Then the links are added as attachments
1227 * @param array $object The raw object
1228 * @param array $object_data The parsed object data for later processing
1229 * @return array the object data
1231 private static function processAttachmentUrls(array $object, array $object_data) {
1232 // Check if this is some url with multiple links
1233 if (empty($object['as:url'])) {
1234 return $object_data;
1237 $urls = $object['as:url'];
1238 $keys = array_keys($urls);
1239 if (!is_numeric(array_pop($keys))) {
1240 return $object_data;
1245 foreach ($urls as $url) {
1246 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1250 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1255 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1256 if (empty($mediatype)) {
1260 if ($mediatype == 'text/html') {
1261 $object_data['alternate-url'] = $href;
1264 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1266 if ($filetype == 'audio') {
1267 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1268 } elseif ($filetype == 'video') {
1269 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1270 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1272 // We save bandwidth by using a moderate height (alt least 480 pixel height)
1273 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1274 if (!empty($attachments[$filetype]['height']) &&
1275 ($height > $attachments[$filetype]['height']) && ($attachments[$filetype]['height'] >= 480)) {
1279 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1280 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1281 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1283 // For Torrent links we always store the highest resolution
1284 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1288 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1292 foreach ($attachments as $type => $attachment) {
1293 $object_data['attachments'][] = ['type' => $type,
1294 'mediaType' => $attachment['type'],
1295 'height' => $attachment['height'],
1296 'size' => $attachment['size'],
1298 'url' => $attachment['url']];
1300 return $object_data;
1304 * Fetches data from the object part of an activity
1306 * @param array $object
1309 * @throws \Exception
1311 private static function processObject($object)
1313 if (!JsonLD::fetchElement($object, '@id')) {
1318 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1319 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1320 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1322 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1323 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1324 $object_data['reply-to-id'] = $object_data['id'];
1326 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1327 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1328 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1329 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1330 $object_data['reply-to-id'] = $replyToId;
1334 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1335 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1337 if (empty($object_data['updated'])) {
1338 $object_data['updated'] = $object_data['published'];
1341 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1342 $object_data['published'] = $object_data['updated'];
1345 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1346 if (empty($actor)) {
1347 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1350 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1351 $location = JsonLD::fetchElement($location, 'location', '@value');
1353 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1354 // down to HTML and then finally format to plaintext.
1355 $location = Markdown::convert($location);
1356 $location = BBCode::convert($location);
1357 $location = HTML::toPlaintext($location);
1360 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1361 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1362 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1363 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1364 $object_data['actor'] = $object_data['author'] = $actor;
1365 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1366 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1367 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1368 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1369 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1370 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1371 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1372 $object_data = self::getSource($object, $object_data);
1373 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1374 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1375 $object_data['location'] = $location;
1376 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1377 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1378 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1379 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1380 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1381 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1382 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1383 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1384 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1385 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1386 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1388 // Special treatment for Hubzilla links
1389 if (is_array($object_data['alternate-url'])) {
1390 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1392 if (!is_string($object_data['alternate-url'])) {
1393 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1397 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1398 $object_data = self::processAttachmentUrls($object, $object_data);
1401 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1402 $receivers = $reception_types = [];
1403 foreach ($receiverdata as $key => $data) {
1404 $receivers[$key] = $data['uid'];
1405 $reception_types[$data['uid']] = $data['type'] ?? 0;
1408 $object_data['receiver'] = $receivers;
1409 $object_data['reception_type'] = $reception_types;
1411 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1412 unset($object_data['receiver'][-1]);
1413 unset($object_data['reception_type'][-1]);
1415 // Common object data:
1418 // @context, type, actor, signature, mediaType, duration, replies, icon
1420 // Also missing: (Defined in the standard, but currently unused)
1421 // audience, preview, endTime, startTime, image
1426 // contentMap, announcement_count, announcements, context_id, likes, like_count
1427 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1432 // category, licence, language, commentsEnabled
1435 // views, waitTranscoding, state, support, subtitleLanguage
1436 // likes, dislikes, shares, comments
1438 return $object_data;