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 APContact::unMarkForArchival($apcontact);
109 $http_signer = HTTPSignature::getSigner($body, $header);
110 if (empty($http_signer)) {
111 Logger::warning('Invalid HTTP signature, message will be discarded.');
114 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
117 $signer = [$http_signer];
119 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
121 if (LDSignature::isSigned($activity)) {
122 $ld_signer = LDSignature::getSigner($activity);
123 if (empty($ld_signer)) {
124 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
125 } elseif ($ld_signer != $http_signer) {
126 $signer[] = $ld_signer;
128 if (!empty($ld_signer && ($actor == $http_signer))) {
129 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
130 $trust_source = true;
131 } elseif (!empty($ld_signer)) {
132 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
133 $trust_source = true;
134 } elseif ($actor == $http_signer) {
135 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
136 $trust_source = true;
138 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
139 $trust_source = false;
141 } elseif ($actor == $http_signer) {
142 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
143 $trust_source = true;
145 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
146 $trust_source = false;
149 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
153 * Process incoming posts from relays
155 * @param array $activity
156 * @param string $actor
159 private static function processRelayPost(array $activity, string $actor)
161 $type = JsonLD::fetchElement($activity, '@type');
163 Logger::info('Empty type', ['activity' => $activity]);
167 if ($type != 'as:Announce') {
168 Logger::info('Not an announcement', ['activity' => $activity]);
172 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
173 if (empty($object_id)) {
174 Logger::info('No object id found', ['activity' => $activity]);
178 $contact = Contact::getByURL($actor);
179 if (empty($contact)) {
180 Logger::info('Relay contact not found', ['actor' => $actor]);
184 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
185 Logger::notice('Relay is no sharer', ['actor' => $actor]);
189 Logger::info('Got relayed message id', ['id' => $object_id]);
191 $item_id = Item::searchByLink($object_id);
193 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
197 $id = Processor::fetchMissingActivity($object_id, [], $actor);
199 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
203 $item_id = Item::searchByLink($object_id);
205 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
207 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
212 * Fetches the object type for a given object id
214 * @param array $activity
215 * @param string $object_id Object ID of the the provided object
216 * @param integer $uid User ID
218 * @return string with object type
219 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
220 * @throws \ImagickException
222 private static function fetchObjectType($activity, $object_id, $uid = 0)
224 if (!empty($activity['as:object'])) {
225 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
226 if (!empty($object_type)) {
231 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
232 // We just assume "note" since it doesn't make a difference for the further processing
236 $profile = APContact::getByURL($object_id);
237 if (!empty($profile['type'])) {
238 APContact::unMarkForArchival($profile);
239 return 'as:' . $profile['type'];
242 $data = ActivityPub::fetchContent($object_id, $uid);
244 $object = JsonLD::compact($data);
245 $type = JsonLD::fetchElement($object, '@type');
255 * Prepare the object array
257 * @param array $activity Array with activity data
258 * @param integer $uid User ID
259 * @param boolean $push Message had been pushed to our system
260 * @param boolean $trust_source Do we trust the source?
262 * @return array with object data
263 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
264 * @throws \ImagickException
266 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
268 $id = JsonLD::fetchElement($activity, '@id');
269 if (!empty($id) && !$trust_source) {
270 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
271 if (!empty($fetched_activity)) {
272 $object = JsonLD::compact($fetched_activity);
273 $fetched_id = JsonLD::fetchElement($object, '@id');
274 if ($fetched_id == $id) {
275 Logger::info('Activity had been fetched successfully', ['id' => $id]);
276 $trust_source = true;
279 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
282 Logger::info('Activity could not been fetched', ['id' => $id]);
286 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
288 Logger::info('Empty actor', ['activity' => $activity]);
292 $type = JsonLD::fetchElement($activity, '@type');
294 // Fetch all receivers from to, cc, bto and bcc
295 $receiverdata = self::getReceivers($activity, $actor);
296 $receivers = $reception_types = [];
297 foreach ($receiverdata as $key => $data) {
298 $receivers[$key] = $data['uid'];
299 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
302 // When it is a delivery to a personal inbox we add that user to the receivers
304 $additional = [$uid => $uid];
305 $receivers = array_replace($receivers, $additional);
306 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]))) {
307 $reception_types[$uid] = self::TARGET_BCC;
310 // We possibly need some user to fetch private content,
311 // so we fetch the first out ot the list.
312 $uid = self::getFirstUserFromReceivers($receivers);
315 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
316 if (empty($object_id)) {
317 Logger::log('No object found', Logger::DEBUG);
321 if (!is_string($object_id)) {
322 Logger::info('Invalid object id', ['object' => $object_id]);
326 $object_type = self::fetchObjectType($activity, $object_id, $uid);
328 // Fetch the content only on activities where this matters
329 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
330 // Always fetch on "Announce"
331 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
332 if (empty($object_data)) {
333 Logger::log("Object data couldn't be processed", Logger::DEBUG);
337 $object_data['object_id'] = $object_id;
339 if ($type == 'as:Announce') {
340 $object_data['push'] = false;
342 $object_data['push'] = $push;
345 // Test if it is an answer to a mail
346 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
347 $object_data['directmessage'] = true;
349 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
351 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
352 // Create a mostly empty array out of the activity data (instead of the object).
353 // This way we later don't have to check for the existence of ech individual array element.
354 $object_data = self::processObject($activity);
355 $object_data['name'] = $type;
356 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
357 $object_data['object_id'] = $object_id;
358 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
359 } elseif (in_array($type, ['as:Add'])) {
361 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
362 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
363 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
364 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
365 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
368 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
369 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
370 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
371 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
372 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
374 // An Undo is done on the object of an object, so we need that type as well
375 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
376 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
380 $object_data = self::addActivityFields($object_data, $activity);
382 if (empty($object_data['object_type'])) {
383 $object_data['object_type'] = $object_type;
386 $object_data['type'] = $type;
387 $object_data['actor'] = $actor;
388 $object_data['item_receiver'] = $receivers;
389 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
390 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
392 $author = $object_data['author'] ?? $actor;
393 if (!empty($author) && !empty($object_data['id'])) {
394 $author_host = parse_url($author, PHP_URL_HOST);
395 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
396 if ($author_host == $id_host) {
397 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
399 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
400 $trust_source = false;
404 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
410 * Fetches the first user id from the receiver array
412 * @param array $receivers Array with receivers
413 * @return integer user id;
415 public static function getFirstUserFromReceivers($receivers)
417 foreach ($receivers as $receiver) {
418 if (!empty($receiver)) {
426 * Processes the activity object
428 * @param array $activity Array with activity data
429 * @param string $body
430 * @param integer $uid User ID
431 * @param boolean $trust_source Do we trust the source?
432 * @param boolean $push Message had been pushed to our system
435 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
437 $type = JsonLD::fetchElement($activity, '@type');
439 Logger::info('Empty type', ['activity' => $activity]);
443 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
444 Logger::info('Empty object', ['activity' => $activity]);
448 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
450 Logger::info('Empty actor', ['activity' => $activity]);
454 if (is_array($activity['as:object'])) {
455 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
460 // Test the provided signatures against the actor and "attributedTo"
462 if (!empty($attributed_to) && !empty($actor)) {
463 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
465 $trust_source = in_array($actor, $signer);
469 // $trust_source is called by reference and is set to true if the content was retrieved successfully
470 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
471 if (empty($object_data)) {
472 Logger::info('No object data found', ['activity' => $activity]);
476 if (!$trust_source) {
477 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
481 if (!empty($body) && empty($object_data['raw'])) {
482 $object_data['raw'] = $body;
485 // Internal flag for thread completion. See Processor.php
486 if (!empty($activity['thread-completion'])) {
487 $object_data['thread-completion'] = $activity['thread-completion'];
490 // Internal flag for posts that arrived via relay
491 if (!empty($activity['from-relay'])) {
492 $object_data['from-relay'] = $activity['from-relay'];
497 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
498 $item = ActivityPub\Processor::createItem($object_data);
499 ActivityPub\Processor::postItem($object_data, $item);
504 if ($object_data['object_type'] == 'as:tag') {
505 ActivityPub\Processor::addTag($object_data);
510 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
511 $object_data['thread-completion'] = Contact::getIdForURL($actor);
513 $item = ActivityPub\Processor::createItem($object_data);
518 $item['post-type'] = Item::PT_ANNOUNCEMENT;
519 ActivityPub\Processor::postItem($object_data, $item);
521 $announce_object_data = self::processObject($activity);
522 $announce_object_data['name'] = $type;
523 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
524 $announce_object_data['object_id'] = $object_data['object_id'];
525 $announce_object_data['object_type'] = $object_data['object_type'];
526 $announce_object_data['push'] = $push;
529 $announce_object_data['raw'] = $body;
532 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
537 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
538 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
543 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
544 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
548 case 'as:TentativeAccept':
549 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
550 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
555 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
556 ActivityPub\Processor::updateItem($object_data);
557 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
558 ActivityPub\Processor::updatePerson($object_data);
563 if ($object_data['object_type'] == 'as:Tombstone') {
564 ActivityPub\Processor::deleteItem($object_data);
565 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
566 ActivityPub\Processor::deletePerson($object_data);
571 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
572 ActivityPub\Processor::followUser($object_data);
573 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
574 $object_data['reply-to-id'] = $object_data['object_id'];
575 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
580 if ($object_data['object_type'] == 'as:Follow') {
581 ActivityPub\Processor::acceptFollowUser($object_data);
582 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
583 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
588 if ($object_data['object_type'] == 'as:Follow') {
589 ActivityPub\Processor::rejectFollowUser($object_data);
590 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
591 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
596 if (($object_data['object_type'] == 'as:Follow') &&
597 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
598 ActivityPub\Processor::undoFollowUser($object_data);
599 } elseif (($object_data['object_type'] == 'as:Accept') &&
600 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
601 ActivityPub\Processor::rejectFollowUser($object_data);
602 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
603 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
604 ActivityPub\Processor::undoActivity($object_data);
609 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
615 * Fetch the receiver list from an activity array
617 * @param array $activity
618 * @param string $actor
620 * @param boolean $fetch_unlisted
622 * @return array with receivers (user id)
625 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
627 $reply = $receivers = [];
629 // When it is an answer, we inherite the receivers from the parent
630 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
631 if (!empty($replyto)) {
634 // Fix possibly wrong item URI (could be an answer to a plink uri)
635 $fixedReplyTo = Item::getURIByLink($replyto);
636 if (!empty($fixedReplyTo)) {
637 $reply[] = $fixedReplyTo;
641 // Fetch all posts that refer to the object id
642 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
643 if (!empty($object_id)) {
644 $reply[] = $object_id;
647 if (!empty($reply)) {
648 $parents = Item::select(['uid'], ['uri' => $reply]);
649 while ($parent = Item::fetch($parents)) {
650 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
654 if (!empty($actor)) {
655 $profile = APContact::getByURL($actor);
656 $followers = $profile['followers'] ?? '';
658 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
660 Logger::info('Empty actor', ['activity' => $activity]);
664 // We have to prevent false follower assumptions upon thread completions
665 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
667 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
668 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
669 if (empty($receiver_list)) {
673 foreach ($receiver_list as $receiver) {
674 if ($receiver == self::PUBLIC_COLLECTION) {
675 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
678 // Add receiver "-1" for unlisted posts
679 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
680 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
683 // Fetch the receivers for the public and the followers collection
684 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
685 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
689 // Fetching all directly addressed receivers
690 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
691 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
692 if (!DBA::isResult($contact)) {
696 // Check if the potential receiver is following the actor
697 // Exception: The receiver is targetted via "to" or this is a comment
698 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
699 $networks = Protocol::FEDERATED;
700 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
701 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
703 // Forum posts are only accepted from forum contacts
704 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
705 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
708 if (!DBA::exists('contact', $condition)) {
713 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
714 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
717 $type = self::TARGET_TO;
720 $type = self::TARGET_CC;
723 $type = self::TARGET_BTO;
726 $type = self::TARGET_BCC;
730 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
735 self::switchContacts($receivers, $actor);
741 * Fetch the receiver list of a given actor
743 * @param string $actor
745 * @param array $receivers
746 * @param integer $target_type
748 * @return array with receivers (user id)
751 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
753 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
754 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
756 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
757 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
758 while ($contact = DBA::fetch($contacts)) {
759 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
760 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
763 DBA::close($contacts);
765 // The queries are split because of performance issues
766 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
767 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
768 while ($contact = DBA::fetch($contacts)) {
769 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
770 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
773 DBA::close($contacts);
778 * Tests if the contact is a valid receiver for this actor
780 * @param array $contact
781 * @param string $actor
784 * @return bool with receivers (user id)
787 private static function isValidReceiverForActor($contact, $tags)
789 // Are we following the contact? Then this is a valid receiver
790 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
794 // When the possible receiver isn't a community, then it is no valid receiver
795 $owner = User::getOwnerDataById($contact['uid']);
796 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
800 // Is the community account tagged?
801 foreach ($tags as $tag) {
802 if ($tag['type'] != 'Mention') {
806 if (Strings::compareLink($tag['href'], $owner['url'])) {
815 * Switches existing contacts to ActivityPub
817 * @param integer $cid Contact ID
818 * @param integer $uid User ID
819 * @param string $url Profile URL
820 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
821 * @throws \ImagickException
823 public static function switchContact($cid, $uid, $url)
825 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
826 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
830 if (Contact::updateFromProbe($cid)) {
831 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
834 // Send a new follow request to be sure that the connection still exists
835 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
836 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
837 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
846 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
847 * @throws \ImagickException
849 private static function switchContacts($receivers, $actor)
855 foreach ($receivers as $receiver) {
856 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
857 if (DBA::isResult($contact)) {
858 self::switchContact($contact['id'], $receiver['uid'], $actor);
861 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
862 if (DBA::isResult($contact)) {
863 self::switchContact($contact['id'], $receiver['uid'], $actor);
871 * @param $object_data
872 * @param array $activity
876 private static function addActivityFields($object_data, $activity)
878 if (!empty($activity['published']) && empty($object_data['published'])) {
879 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
882 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
883 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
886 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
887 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
889 if (!empty($object_data['object_id'])) {
890 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
891 $objectId = Item::getURIByLink($object_data['object_id']);
892 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
893 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
894 $object_data['object_id'] = $objectId;
902 * Fetches the object data from external ressources if needed
904 * @param string $object_id Object ID of the the provided object
905 * @param array $object The provided object array
906 * @param boolean $trust_source Do we trust the provided object?
907 * @param integer $uid User ID for the signature that we use to fetch data
909 * @return array|false with trusted and valid object data
910 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
911 * @throws \ImagickException
913 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
915 // By fetching the type we check if the object is complete.
916 $type = JsonLD::fetchElement($object, '@type');
918 if (!$trust_source || empty($type)) {
919 $data = ActivityPub::fetchContent($object_id, $uid);
921 $object = JsonLD::compact($data);
922 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
924 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
926 $item = Item::selectFirst([], ['uri' => $object_id]);
927 if (!DBA::isResult($item)) {
928 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
931 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
932 $data = ActivityPub\Transmitter::createNote($item);
933 $object = JsonLD::compact($data);
936 $id = JsonLD::fetchElement($object, '@id');
938 Logger::info('Empty id');
942 if ($id != $object_id) {
943 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
947 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
950 $type = JsonLD::fetchElement($object, '@type');
952 Logger::info('Empty type');
956 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
957 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
958 $object_data = self::processObject($object);
961 $object_data['raw'] = json_encode($data);
966 if ($type == 'as:Announce') {
967 $object_id = JsonLD::fetchElement($object, 'object', '@id');
968 if (empty($object_id) || !is_string($object_id)) {
971 return self::fetchObject($object_id, [], false, $uid);
974 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
979 * Convert tags from JSON-LD format into a simplified format
981 * @param array $tags Tags in JSON-LD format
983 * @return array with tags in a simplified format
985 public static function processTags(array $tags)
989 foreach ($tags as $tag) {
994 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
995 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
996 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
998 if (empty($element['type'])) {
1002 if (empty($element['href'])) {
1003 $element['href'] = $element['name'];
1006 $taglist[] = $element;
1012 * Convert emojis from JSON-LD format into a simplified format
1014 * @param array $emojis
1015 * @return array with emojis in a simplified format
1017 private static function processEmojis(array $emojis)
1021 foreach ($emojis as $emoji) {
1022 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1026 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1027 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1030 $emojilist[] = $element;
1037 * Convert attachments from JSON-LD format into a simplified format
1039 * @param array $attachments Attachments in JSON-LD format
1041 * @return array Attachments in a simplified format
1043 private static function processAttachments(array $attachments)
1047 // Removes empty values
1048 $attachments = array_filter($attachments);
1050 foreach ($attachments as $attachment) {
1051 switch (JsonLD::fetchElement($attachment, '@type')) {
1056 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1057 foreach ($urls as $url) {
1058 // Single scalar URL case
1059 if (is_string($url)) {
1064 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1065 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1066 if (Strings::startsWith($mediaType, 'image')) {
1075 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1076 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1078 'image' => $pageImage,
1083 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1084 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1085 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1086 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1090 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1091 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1092 $imagePreviewUrl = null;
1094 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1095 $imageVariants = [];
1096 $previewVariants = [];
1097 foreach ($urls as $url) {
1098 // Scalar URL, no discrimination possible
1099 if (is_string($url)) {
1100 $imageFullUrl = $url;
1104 // Not sure what to do with a different Link media type than the base Image, we skip
1105 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1109 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1111 // Default URL choice if no discriminating width is provided
1112 $imageFullUrl = $href ?? $imageFullUrl;
1114 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1116 if ($href && $width) {
1117 $imageVariants[$width] = $href;
1118 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1119 $previewVariants[abs(632 - $width)] = $href;
1123 if ($imageVariants) {
1124 // Taking the maximum size image
1125 ksort($imageVariants);
1126 $imageFullUrl = array_pop($imageVariants);
1128 // Taking the minimum number distance to the target distance
1129 ksort($previewVariants);
1130 $imagePreviewUrl = array_shift($previewVariants);
1133 unset($imageVariants);
1134 unset($previewVariants);
1138 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1139 'mediaType' => $mediaType,
1140 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1141 'url' => $imageFullUrl,
1142 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1147 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1148 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1149 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1150 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1159 * Fetch the original source or content with the "language" Markdown or HTML
1161 * @param array $object
1162 * @param array $object_data
1165 * @throws \Exception
1167 private static function getSource($object, $object_data)
1169 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1170 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1171 if (!empty($object_data['source'])) {
1172 return $object_data;
1175 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1176 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1177 if (!empty($object_data['source'])) {
1178 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1179 return $object_data;
1182 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1183 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1184 if (!empty($object_data['source'])) {
1185 $object_data['source'] = HTML::toBBCode($object_data['source']);
1186 return $object_data;
1189 return $object_data;
1193 * Check if the "as:url" element is an array with multiple links
1194 * This is the case with audio and video posts.
1195 * Then the links are added as attachments
1197 * @param array $object The raw object
1198 * @param array $object_data The parsed object data for later processing
1199 * @return array the object data
1201 private static function processAttachmentUrls(array $object, array $object_data) {
1202 // Check if this is some url with multiple links
1203 if (empty($object['as:url'])) {
1204 return $object_data;
1207 $urls = $object['as:url'];
1208 $keys = array_keys($urls);
1209 if (!is_numeric(array_pop($keys))) {
1210 return $object_data;
1215 foreach ($urls as $url) {
1216 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1220 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1225 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1226 if (empty($mediatype)) {
1230 if ($mediatype == 'text/html') {
1231 $object_data['alternate-url'] = $href;
1234 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1236 if ($filetype == 'audio') {
1237 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1238 } elseif ($filetype == 'video') {
1239 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1240 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1242 // We save bandwidth by using a moderate height (alt least 480 pixel height)
1243 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1244 if (!empty($attachments[$filetype]['height']) &&
1245 ($height > $attachments[$filetype]['height']) && ($attachments[$filetype]['height'] >= 480)) {
1249 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1250 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1251 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1253 // For Torrent links we always store the highest resolution
1254 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1258 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1262 foreach ($attachments as $type => $attachment) {
1263 $object_data['attachments'][] = ['type' => $type,
1264 'mediaType' => $attachment['type'],
1265 'height' => $attachment['height'],
1266 'size' => $attachment['size'],
1268 'url' => $attachment['url']];
1270 return $object_data;
1274 * Fetches data from the object part of an activity
1276 * @param array $object
1279 * @throws \Exception
1281 private static function processObject($object)
1283 if (!JsonLD::fetchElement($object, '@id')) {
1288 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1289 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1290 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1292 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1293 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1294 $object_data['reply-to-id'] = $object_data['id'];
1296 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1297 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1298 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1299 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1300 $object_data['reply-to-id'] = $replyToId;
1304 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1305 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1307 if (empty($object_data['updated'])) {
1308 $object_data['updated'] = $object_data['published'];
1311 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1312 $object_data['published'] = $object_data['updated'];
1315 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1316 if (empty($actor)) {
1317 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1320 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1321 $location = JsonLD::fetchElement($location, 'location', '@value');
1323 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1324 // down to HTML and then finally format to plaintext.
1325 $location = Markdown::convert($location);
1326 $location = BBCode::convert($location);
1327 $location = HTML::toPlaintext($location);
1330 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1331 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1332 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1333 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1334 $object_data['actor'] = $object_data['author'] = $actor;
1335 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1336 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1337 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1338 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1339 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1340 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1341 $object_data = self::getSource($object, $object_data);
1342 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1343 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1344 $object_data['location'] = $location;
1345 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1346 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1347 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1348 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1349 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1350 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1351 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1352 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1353 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1354 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1356 // Special treatment for Hubzilla links
1357 if (is_array($object_data['alternate-url'])) {
1358 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1360 if (!is_string($object_data['alternate-url'])) {
1361 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1365 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1366 $object_data = self::processAttachmentUrls($object, $object_data);
1369 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1370 $receivers = $reception_types = [];
1371 foreach ($receiverdata as $key => $data) {
1372 $receivers[$key] = $data['uid'];
1373 $reception_types[$data['uid']] = $data['type'] ?? 0;
1376 $object_data['receiver'] = $receivers;
1377 $object_data['reception_type'] = $reception_types;
1379 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1380 unset($object_data['receiver'][-1]);
1381 unset($object_data['reception_type'][-1]);
1383 // Common object data:
1386 // @context, type, actor, signature, mediaType, duration, replies, icon
1388 // Also missing: (Defined in the standard, but currently unused)
1389 // audience, preview, endTime, startTime, image
1394 // contentMap, announcement_count, announcements, context_id, likes, like_count
1395 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1400 // category, licence, language, commentsEnabled
1403 // views, waitTranscoding, state, support, subtitleLanguage
1404 // likes, dislikes, shares, comments
1406 return $object_data;