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);
107 $http_signer = HTTPSignature::getSigner($body, $header);
108 if (empty($http_signer)) {
109 Logger::warning('Invalid HTTP signature, message will be discarded.');
112 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
115 $signer = [$http_signer];
117 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
119 if (LDSignature::isSigned($activity)) {
120 $ld_signer = LDSignature::getSigner($activity);
121 if (empty($ld_signer)) {
122 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
123 } elseif ($ld_signer != $http_signer) {
124 $signer[] = $ld_signer;
126 if (!empty($ld_signer && ($actor == $http_signer))) {
127 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
128 $trust_source = true;
129 } elseif (!empty($ld_signer)) {
130 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
131 $trust_source = true;
132 } elseif ($actor == $http_signer) {
133 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
134 $trust_source = true;
136 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
137 $trust_source = false;
139 } elseif ($actor == $http_signer) {
140 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
141 $trust_source = true;
143 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
144 $trust_source = false;
147 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
151 * Process incoming posts from relays
153 * @param array $activity
156 private static function processRelayPost(array $activity)
158 $type = JsonLD::fetchElement($activity, '@type');
160 Logger::info('Empty type', ['activity' => $activity]);
164 if ($type != 'as:Announce') {
165 Logger::info('Not an announcement', ['activity' => $activity]);
169 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
170 if (empty($object_id)) {
171 Logger::info('No object id found', ['activity' => $activity]);
175 Logger::info('Got relayed message id', ['id' => $object_id]);
177 $item_id = Item::searchByLink($object_id);
179 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
183 Processor::fetchMissingActivity($object_id);
185 $item_id = Item::searchByLink($object_id);
187 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
189 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
194 * Fetches the object type for a given object id
196 * @param array $activity
197 * @param string $object_id Object ID of the the provided object
198 * @param integer $uid User ID
200 * @return string with object type
201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
202 * @throws \ImagickException
204 private static function fetchObjectType($activity, $object_id, $uid = 0)
206 if (!empty($activity['as:object'])) {
207 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
208 if (!empty($object_type)) {
213 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
214 // We just assume "note" since it doesn't make a difference for the further processing
218 $profile = APContact::getByURL($object_id);
219 if (!empty($profile['type'])) {
220 return 'as:' . $profile['type'];
223 $data = ActivityPub::fetchContent($object_id, $uid);
225 $object = JsonLD::compact($data);
226 $type = JsonLD::fetchElement($object, '@type');
236 * Prepare the object array
238 * @param array $activity Array with activity data
239 * @param integer $uid User ID
240 * @param boolean $push Message had been pushed to our system
241 * @param boolean $trust_source Do we trust the source?
243 * @return array with object data
244 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
245 * @throws \ImagickException
247 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
249 $id = JsonLD::fetchElement($activity, '@id');
250 if (!empty($id) && !$trust_source) {
251 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
252 if (!empty($fetched_activity)) {
253 $object = JsonLD::compact($fetched_activity);
254 $fetched_id = JsonLD::fetchElement($object, '@id');
255 if ($fetched_id == $id) {
256 Logger::info('Activity had been fetched successfully', ['id' => $id]);
257 $trust_source = true;
260 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
263 Logger::info('Activity could not been fetched', ['id' => $id]);
267 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
269 Logger::info('Empty actor', ['activity' => $activity]);
273 $type = JsonLD::fetchElement($activity, '@type');
275 // Fetch all receivers from to, cc, bto and bcc
276 $receiverdata = self::getReceivers($activity, $actor);
277 $receivers = $reception_types = [];
278 foreach ($receiverdata as $key => $data) {
279 $receivers[$key] = $data['uid'];
280 $reception_types[$data['uid']] = $data['type'] ?? 0;
283 // When it is a delivery to a personal inbox we add that user to the receivers
285 $additional = ['uid:' . $uid => $uid];
286 $receivers = array_merge($receivers, $additional);
287 if (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
288 $reception_types[$uid] = self::TARGET_BCC;
291 // We possibly need some user to fetch private content,
292 // so we fetch the first out ot the list.
293 $uid = self::getFirstUserFromReceivers($receivers);
296 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
297 if (empty($object_id)) {
298 Logger::log('No object found', Logger::DEBUG);
302 if (!is_string($object_id)) {
303 Logger::info('Invalid object id', ['object' => $object_id]);
307 $object_type = self::fetchObjectType($activity, $object_id, $uid);
309 // Fetch the content only on activities where this matters
310 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
311 // Always fetch on "Announce"
312 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
313 if (empty($object_data)) {
314 Logger::log("Object data couldn't be processed", Logger::DEBUG);
318 $object_data['object_id'] = $object_id;
320 if ($type == 'as:Announce') {
321 $object_data['push'] = false;
323 $object_data['push'] = $push;
326 // Test if it is an answer to a mail
327 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
328 $object_data['directmessage'] = true;
330 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
332 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
333 // Create a mostly empty array out of the activity data (instead of the object).
334 // This way we later don't have to check for the existence of ech individual array element.
335 $object_data = self::processObject($activity);
336 $object_data['name'] = $type;
337 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
338 $object_data['object_id'] = $object_id;
339 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
340 } elseif (in_array($type, ['as:Add'])) {
342 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
343 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
344 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
345 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
346 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
349 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
350 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
351 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
352 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
353 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
355 // An Undo is done on the object of an object, so we need that type as well
356 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
357 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
361 $object_data = self::addActivityFields($object_data, $activity);
363 if (empty($object_data['object_type'])) {
364 $object_data['object_type'] = $object_type;
367 $object_data['type'] = $type;
368 $object_data['actor'] = $actor;
369 $object_data['item_receiver'] = $receivers;
370 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
371 $object_data['reception_type'] = array_merge($object_data['reception_type'] ?? [], $reception_types);
373 $author = $object_data['author'] ?? $actor;
374 if (!empty($author) && !empty($object_data['id'])) {
375 $author_host = parse_url($author, PHP_URL_HOST);
376 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
377 if ($author_host == $id_host) {
378 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
380 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
381 $trust_source = false;
385 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
391 * Fetches the first user id from the receiver array
393 * @param array $receivers Array with receivers
394 * @return integer user id;
396 public static function getFirstUserFromReceivers($receivers)
398 foreach ($receivers as $receiver) {
399 if (!empty($receiver)) {
407 * Processes the activity object
409 * @param array $activity Array with activity data
410 * @param string $body
411 * @param integer $uid User ID
412 * @param boolean $trust_source Do we trust the source?
413 * @param boolean $push Message had been pushed to our system
416 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
418 $type = JsonLD::fetchElement($activity, '@type');
420 Logger::info('Empty type', ['activity' => $activity]);
424 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
425 Logger::info('Empty object', ['activity' => $activity]);
429 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
431 Logger::info('Empty actor', ['activity' => $activity]);
435 if (is_array($activity['as:object'])) {
436 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
441 // Test the provided signatures against the actor and "attributedTo"
443 if (!empty($attributed_to) && !empty($actor)) {
444 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
446 $trust_source = in_array($actor, $signer);
450 // $trust_source is called by reference and is set to true if the content was retrieved successfully
451 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
452 if (empty($object_data)) {
453 Logger::info('No object data found', ['activity' => $activity]);
457 if (!$trust_source) {
458 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
462 if (!empty($body) && empty($object_data['raw'])) {
463 $object_data['raw'] = $body;
466 // Internal flag for thread completion. See Processor.php
467 if (!empty($activity['thread-completion'])) {
468 $object_data['thread-completion'] = $activity['thread-completion'];
473 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
474 $item = ActivityPub\Processor::createItem($object_data);
475 ActivityPub\Processor::postItem($object_data, $item);
480 if ($object_data['object_type'] == 'as:tag') {
481 ActivityPub\Processor::addTag($object_data);
486 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
487 $object_data['thread-completion'] = true;
489 $item = ActivityPub\Processor::createItem($object_data);
494 $item['post-type'] = Item::PT_ANNOUNCEMENT;
495 ActivityPub\Processor::postItem($object_data, $item);
497 $announce_object_data = self::processObject($activity);
498 $announce_object_data['name'] = $type;
499 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
500 $announce_object_data['object_id'] = $object_data['object_id'];
501 $announce_object_data['object_type'] = $object_data['object_type'];
502 $announce_object_data['push'] = $push;
505 $announce_object_data['raw'] = $body;
508 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
513 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
514 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
519 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
520 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
524 case 'as:TentativeAccept':
525 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
526 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
531 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
532 ActivityPub\Processor::updateItem($object_data);
533 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
534 ActivityPub\Processor::updatePerson($object_data);
539 if ($object_data['object_type'] == 'as:Tombstone') {
540 ActivityPub\Processor::deleteItem($object_data);
541 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
542 ActivityPub\Processor::deletePerson($object_data);
547 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
548 ActivityPub\Processor::followUser($object_data);
549 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
550 $object_data['reply-to-id'] = $object_data['object_id'];
551 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
556 if ($object_data['object_type'] == 'as:Follow') {
557 ActivityPub\Processor::acceptFollowUser($object_data);
558 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
559 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
564 if ($object_data['object_type'] == 'as:Follow') {
565 ActivityPub\Processor::rejectFollowUser($object_data);
566 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
567 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
572 if (($object_data['object_type'] == 'as:Follow') &&
573 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
574 ActivityPub\Processor::undoFollowUser($object_data);
575 } elseif (($object_data['object_type'] == 'as:Accept') &&
576 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
577 ActivityPub\Processor::rejectFollowUser($object_data);
578 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
579 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
580 ActivityPub\Processor::undoActivity($object_data);
585 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
591 * Fetch the receiver list from an activity array
593 * @param array $activity
594 * @param string $actor
596 * @param boolean $fetch_unlisted
598 * @return array with receivers (user id)
601 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
603 $reply = $receivers = [];
605 // When it is an answer, we inherite the receivers from the parent
606 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
607 if (!empty($replyto)) {
610 // Fix possibly wrong item URI (could be an answer to a plink uri)
611 $fixedReplyTo = Item::getURIByLink($replyto);
612 if (!empty($fixedReplyTo)) {
613 $reply[] = $fixedReplyTo;
617 // Fetch all posts that refer to the object id
618 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
619 if (!empty($object_id)) {
620 $reply[] = $object_id;
623 if (!empty($reply)) {
624 $parents = Item::select(['uid'], ['uri' => $reply]);
625 while ($parent = Item::fetch($parents)) {
626 $receivers['uid:' . $parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
630 if (!empty($actor)) {
631 $profile = APContact::getByURL($actor);
632 $followers = $profile['followers'] ?? '';
634 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
636 Logger::info('Empty actor', ['activity' => $activity]);
640 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
641 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
642 if (empty($receiver_list)) {
646 foreach ($receiver_list as $receiver) {
647 if ($receiver == self::PUBLIC_COLLECTION) {
648 $receivers['uid:0'] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
651 // Add receiver "-1" for unlisted posts
652 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
653 $receivers['uid:-1'] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
656 // Fetch the receivers for the public and the followers collection
657 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
658 $receivers = self::getReceiverForActor($actor, $tags, $receivers);
662 // Fetching all directly addressed receivers
663 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
664 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
665 if (!DBA::isResult($contact)) {
669 // Check if the potential receiver is following the actor
670 // Exception: The receiver is targetted via "to" or this is a comment
671 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
672 $networks = Protocol::FEDERATED;
673 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
674 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
676 // Forum posts are only accepted from forum contacts
677 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
678 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
681 if (!DBA::exists('contact', $condition)) {
686 $type = $receivers['uid:' . $contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
687 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
690 $type = self::TARGET_TO;
693 $type = self::TARGET_CC;
696 $type = self::TARGET_BTO;
699 $type = self::TARGET_BCC;
703 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
708 self::switchContacts($receivers, $actor);
714 * Fetch the receiver list of a given actor
716 * @param string $actor
719 * @return array with receivers (user id)
722 private static function getReceiverForActor($actor, $tags, $receivers)
724 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
725 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
727 $condition = DBA::mergeConditions($basecondition, ['nurl' => Strings::normaliseLink($actor)]);
728 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
729 while ($contact = DBA::fetch($contacts)) {
730 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
731 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
734 DBA::close($contacts);
736 // The queries are split because of performance issues
737 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?)", Strings::normaliseLink($actor), $actor]);
738 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
739 while ($contact = DBA::fetch($contacts)) {
740 if (empty($receivers['uid:' . $contact['uid']]) && self::isValidReceiverForActor($contact, $actor, $tags)) {
741 $receivers['uid:' . $contact['uid']] = ['uid' => $contact['uid'], 'type' => self::TARGET_FOLLOWER];
744 DBA::close($contacts);
749 * Tests if the contact is a valid receiver for this actor
751 * @param array $contact
752 * @param string $actor
755 * @return bool with receivers (user id)
758 private static function isValidReceiverForActor($contact, $actor, $tags)
760 // Public contacts are no valid receiver
761 if ($contact['uid'] == 0) {
765 // Are we following the contact? Then this is a valid receiver
766 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
770 // When the possible receiver isn't a community, then it is no valid receiver
771 $owner = User::getOwnerDataById($contact['uid']);
772 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
776 // Is the community account tagged?
777 foreach ($tags as $tag) {
778 if ($tag['type'] != 'Mention') {
782 if ($tag['href'] == $owner['url']) {
791 * Switches existing contacts to ActivityPub
793 * @param integer $cid Contact ID
794 * @param integer $uid User ID
795 * @param string $url Profile URL
796 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
797 * @throws \ImagickException
799 public static function switchContact($cid, $uid, $url)
801 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
802 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
806 if (Contact::updateFromProbe($cid)) {
807 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
810 // Send a new follow request to be sure that the connection still exists
811 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
812 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
813 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
822 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
823 * @throws \ImagickException
825 private static function switchContacts($receivers, $actor)
831 foreach ($receivers as $receiver) {
832 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
833 if (DBA::isResult($contact)) {
834 self::switchContact($contact['id'], $receiver['uid'], $actor);
837 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
838 if (DBA::isResult($contact)) {
839 self::switchContact($contact['id'], $receiver['uid'], $actor);
847 * @param $object_data
848 * @param array $activity
852 private static function addActivityFields($object_data, $activity)
854 if (!empty($activity['published']) && empty($object_data['published'])) {
855 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
858 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
859 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
862 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
863 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
865 if (!empty($object_data['object_id'])) {
866 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
867 $objectId = Item::getURIByLink($object_data['object_id']);
868 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
869 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
870 $object_data['object_id'] = $objectId;
878 * Fetches the object data from external ressources if needed
880 * @param string $object_id Object ID of the the provided object
881 * @param array $object The provided object array
882 * @param boolean $trust_source Do we trust the provided object?
883 * @param integer $uid User ID for the signature that we use to fetch data
885 * @return array|false with trusted and valid object data
886 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
887 * @throws \ImagickException
889 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
891 // By fetching the type we check if the object is complete.
892 $type = JsonLD::fetchElement($object, '@type');
894 if (!$trust_source || empty($type)) {
895 $data = ActivityPub::fetchContent($object_id, $uid);
897 $object = JsonLD::compact($data);
898 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
900 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
902 $item = Item::selectFirst([], ['uri' => $object_id]);
903 if (!DBA::isResult($item)) {
904 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
907 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
908 $data = ActivityPub\Transmitter::createNote($item);
909 $object = JsonLD::compact($data);
912 $id = JsonLD::fetchElement($object, '@id');
914 Logger::info('Empty id');
918 if ($id != $object_id) {
919 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
923 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
926 $type = JsonLD::fetchElement($object, '@type');
928 Logger::info('Empty type');
932 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
933 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
934 $object_data = self::processObject($object);
937 $object_data['raw'] = json_encode($data);
942 if ($type == 'as:Announce') {
943 $object_id = JsonLD::fetchElement($object, 'object', '@id');
944 if (empty($object_id) || !is_string($object_id)) {
947 return self::fetchObject($object_id, [], false, $uid);
950 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
955 * Convert tags from JSON-LD format into a simplified format
957 * @param array $tags Tags in JSON-LD format
959 * @return array with tags in a simplified format
961 private static function processTags(array $tags)
965 foreach ($tags as $tag) {
970 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
971 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
972 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
974 if (empty($element['type'])) {
978 if (empty($element['href'])) {
979 $element['href'] = $element['name'];
982 $taglist[] = $element;
988 * Convert emojis from JSON-LD format into a simplified format
990 * @param array $emojis
991 * @return array with emojis in a simplified format
993 private static function processEmojis(array $emojis)
997 foreach ($emojis as $emoji) {
998 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1002 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1003 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1006 $emojilist[] = $element;
1013 * Convert attachments from JSON-LD format into a simplified format
1015 * @param array $attachments Attachments in JSON-LD format
1017 * @return array Attachments in a simplified format
1019 private static function processAttachments(array $attachments)
1023 // Removes empty values
1024 $attachments = array_filter($attachments);
1026 foreach ($attachments as $attachment) {
1027 switch (JsonLD::fetchElement($attachment, '@type')) {
1032 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1033 foreach ($urls as $url) {
1034 // Single scalar URL case
1035 if (is_string($url)) {
1040 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1041 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1042 if (Strings::startsWith($mediaType, 'image')) {
1051 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1052 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1054 'image' => $pageImage,
1059 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1060 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1061 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1062 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1066 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1067 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1068 $imagePreviewUrl = null;
1070 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1071 $imageVariants = [];
1072 $previewVariants = [];
1073 foreach ($urls as $url) {
1074 // Scalar URL, no discrimination possible
1075 if (is_string($url)) {
1076 $imageFullUrl = $url;
1080 // Not sure what to do with a different Link media type than the base Image, we skip
1081 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1085 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1087 // Default URL choice if no discriminating width is provided
1088 $imageFullUrl = $href ?? $imageFullUrl;
1090 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1092 if ($href && $width) {
1093 $imageVariants[$width] = $href;
1094 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1095 $previewVariants[abs(632 - $width)] = $href;
1099 if ($imageVariants) {
1100 // Taking the maximum size image
1101 ksort($imageVariants);
1102 $imageFullUrl = array_pop($imageVariants);
1104 // Taking the minimum number distance to the target distance
1105 ksort($previewVariants);
1106 $imagePreviewUrl = array_shift($previewVariants);
1109 unset($imageVariants);
1110 unset($previewVariants);
1114 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1115 'mediaType' => $mediaType,
1116 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1117 'url' => $imageFullUrl,
1118 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1123 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1124 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1125 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1126 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1135 * Fetch the original source or content with the "language" Markdown or HTML
1137 * @param array $object
1138 * @param array $object_data
1141 * @throws \Exception
1143 private static function getSource($object, $object_data)
1145 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1146 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1147 if (!empty($object_data['source'])) {
1148 return $object_data;
1151 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1152 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1153 if (!empty($object_data['source'])) {
1154 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1155 return $object_data;
1158 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1159 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1160 if (!empty($object_data['source'])) {
1161 $object_data['source'] = HTML::toBBCode($object_data['source']);
1162 return $object_data;
1165 return $object_data;
1169 * Check if the "as:url" element is an array with multiple links
1170 * This is the case with audio and video posts.
1171 * Then the links are added as attachments
1173 * @param array $object The raw object
1174 * @param array $object_data The parsed object data for later processing
1175 * @return array the object data
1177 private static function processAttachmentUrls(array $object, array $object_data) {
1178 // Check if this is some url with multiple links
1179 if (empty($object['as:url'])) {
1180 return $object_data;
1183 $urls = $object['as:url'];
1184 $keys = array_keys($urls);
1185 if (!is_numeric(array_pop($keys))) {
1186 return $object_data;
1191 foreach ($urls as $url) {
1192 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1196 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1201 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1202 if (empty($mediatype)) {
1206 if ($mediatype == 'text/html') {
1207 $object_data['alternate-url'] = $href;
1210 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1212 if ($filetype == 'audio') {
1213 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1214 } elseif ($filetype == 'video') {
1215 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1217 // We save bandwidth by using a moderate height
1218 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1219 if (!empty($attachments[$filetype]['height']) &&
1220 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1224 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1228 foreach ($attachments as $type => $attachment) {
1229 $object_data['attachments'][] = ['type' => $type,
1230 'mediaType' => $attachment['type'],
1232 'url' => $attachment['url']];
1234 return $object_data;
1238 * Fetches data from the object part of an activity
1240 * @param array $object
1243 * @throws \Exception
1245 private static function processObject($object)
1247 if (!JsonLD::fetchElement($object, '@id')) {
1252 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1253 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1254 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1256 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1257 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1258 $object_data['reply-to-id'] = $object_data['id'];
1260 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1261 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1262 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1263 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1264 $object_data['reply-to-id'] = $replyToId;
1268 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1269 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1271 if (empty($object_data['updated'])) {
1272 $object_data['updated'] = $object_data['published'];
1275 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1276 $object_data['published'] = $object_data['updated'];
1279 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1280 if (empty($actor)) {
1281 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1284 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1285 $location = JsonLD::fetchElement($location, 'location', '@value');
1287 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1288 // down to HTML and then finally format to plaintext.
1289 $location = Markdown::convert($location);
1290 $location = BBCode::convert($location);
1291 $location = HTML::toPlaintext($location);
1294 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1295 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1296 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1297 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1298 $object_data['actor'] = $object_data['author'] = $actor;
1299 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1300 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1301 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1302 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1303 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1304 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1305 $object_data = self::getSource($object, $object_data);
1306 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1307 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1308 $object_data['location'] = $location;
1309 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1310 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1311 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1312 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1313 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1314 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1315 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1316 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1317 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1318 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1320 // Special treatment for Hubzilla links
1321 if (is_array($object_data['alternate-url'])) {
1322 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1324 if (!is_string($object_data['alternate-url'])) {
1325 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1329 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1330 $object_data = self::processAttachmentUrls($object, $object_data);
1333 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1334 $receivers = $reception_types = [];
1335 foreach ($receiverdata as $key => $data) {
1336 $receivers[$key] = $data['uid'];
1337 $reception_types[$data['uid']] = $data['type'] ?? 0;
1340 $object_data['receiver'] = $receivers;
1341 $object_data['reception_type'] = $reception_types;
1343 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1344 unset($object_data['receiver']['uid:-1']);
1346 // Common object data:
1349 // @context, type, actor, signature, mediaType, duration, replies, icon
1351 // Also missing: (Defined in the standard, but currently unused)
1352 // audience, preview, endTime, startTime, image
1357 // contentMap, announcement_count, announcements, context_id, likes, like_count
1358 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1363 // category, licence, language, commentsEnabled
1366 // views, waitTranscoding, state, support, subtitleLanguage
1367 // likes, dislikes, shares, comments
1369 return $object_data;