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)) {
103 Logger::notice('Unable to retrieve AP contact for actor', ['actor' => $actor]);
104 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
105 self::processRelayPost($ldactivity, $actor);
108 APContact::unmarkForArchival($apcontact);
111 $http_signer = HTTPSignature::getSigner($body, $header);
112 if (empty($http_signer)) {
113 Logger::warning('Invalid HTTP signature, message will be discarded.');
116 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
119 $signer = [$http_signer];
121 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
123 if (LDSignature::isSigned($activity)) {
124 $ld_signer = LDSignature::getSigner($activity);
125 if (empty($ld_signer)) {
126 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
127 } elseif ($ld_signer != $http_signer) {
128 $signer[] = $ld_signer;
130 if (!empty($ld_signer && ($actor == $http_signer))) {
131 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
132 $trust_source = true;
133 } elseif (!empty($ld_signer)) {
134 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
135 $trust_source = true;
136 } elseif ($actor == $http_signer) {
137 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
138 $trust_source = true;
140 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
141 $trust_source = false;
143 } elseif ($actor == $http_signer) {
144 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
145 $trust_source = true;
147 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
148 $trust_source = false;
151 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
155 * Process incoming posts from relays
157 * @param array $activity
158 * @param string $actor
161 private static function processRelayPost(array $activity, string $actor)
163 $type = JsonLD::fetchElement($activity, '@type');
165 Logger::info('Empty type', ['activity' => $activity]);
169 if ($type != 'as:Announce') {
170 Logger::info('Not an announcement', ['activity' => $activity]);
174 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
175 if (empty($object_id)) {
176 Logger::info('No object id found', ['activity' => $activity]);
180 $contact = Contact::getByURL($actor);
181 if (empty($contact)) {
182 Logger::info('Relay contact not found', ['actor' => $actor]);
186 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
187 Logger::notice('Relay is no sharer', ['actor' => $actor]);
191 Logger::info('Got relayed message id', ['id' => $object_id]);
193 $item_id = Item::searchByLink($object_id);
195 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
199 $id = Processor::fetchMissingActivity($object_id, [], $actor);
201 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
205 $item_id = Item::searchByLink($object_id);
207 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
209 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
214 * Fetches the object type for a given object id
216 * @param array $activity
217 * @param string $object_id Object ID of the the provided object
218 * @param integer $uid User ID
220 * @return string with object type
221 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
222 * @throws \ImagickException
224 private static function fetchObjectType($activity, $object_id, $uid = 0)
226 if (!empty($activity['as:object'])) {
227 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
228 if (!empty($object_type)) {
233 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
234 // We just assume "note" since it doesn't make a difference for the further processing
238 $profile = APContact::getByURL($object_id);
239 if (!empty($profile['type'])) {
240 APContact::unmarkForArchival($profile);
241 return 'as:' . $profile['type'];
244 $data = ActivityPub::fetchContent($object_id, $uid);
246 $object = JsonLD::compact($data);
247 $type = JsonLD::fetchElement($object, '@type');
257 * Prepare the object array
259 * @param array $activity Array with activity data
260 * @param integer $uid User ID
261 * @param boolean $push Message had been pushed to our system
262 * @param boolean $trust_source Do we trust the source?
264 * @return array with object data
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266 * @throws \ImagickException
268 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
270 $id = JsonLD::fetchElement($activity, '@id');
271 if (!empty($id) && !$trust_source) {
272 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
273 if (!empty($fetched_activity)) {
274 $object = JsonLD::compact($fetched_activity);
275 $fetched_id = JsonLD::fetchElement($object, '@id');
276 if ($fetched_id == $id) {
277 Logger::info('Activity had been fetched successfully', ['id' => $id]);
278 $trust_source = true;
281 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
284 Logger::info('Activity could not been fetched', ['id' => $id]);
288 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
290 Logger::info('Empty actor', ['activity' => $activity]);
294 $type = JsonLD::fetchElement($activity, '@type');
296 // Fetch all receivers from to, cc, bto and bcc
297 $receiverdata = self::getReceivers($activity, $actor);
298 $receivers = $reception_types = [];
299 foreach ($receiverdata as $key => $data) {
300 $receivers[$key] = $data['uid'];
301 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
304 // When it is a delivery to a personal inbox we add that user to the receivers
306 $additional = [$uid => $uid];
307 $receivers = array_replace($receivers, $additional);
308 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]))) {
309 $reception_types[$uid] = self::TARGET_BCC;
312 // We possibly need some user to fetch private content,
313 // so we fetch the first out ot the list.
314 $uid = self::getFirstUserFromReceivers($receivers);
317 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
318 if (empty($object_id)) {
319 Logger::log('No object found', Logger::DEBUG);
323 if (!is_string($object_id)) {
324 Logger::info('Invalid object id', ['object' => $object_id]);
328 $object_type = self::fetchObjectType($activity, $object_id, $uid);
330 // Fetch the content only on activities where this matters
331 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
332 // Always fetch on "Announce"
333 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
334 if (empty($object_data)) {
335 Logger::log("Object data couldn't be processed", Logger::DEBUG);
339 $object_data['object_id'] = $object_id;
341 if ($type == 'as:Announce') {
342 $object_data['push'] = false;
344 $object_data['push'] = $push;
347 // Test if it is an answer to a mail
348 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
349 $object_data['directmessage'] = true;
351 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
353 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
354 // Create a mostly empty array out of the activity data (instead of the object).
355 // This way we later don't have to check for the existence of ech individual array element.
356 $object_data = self::processObject($activity);
357 $object_data['name'] = $type;
358 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
359 $object_data['object_id'] = $object_id;
360 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
361 $object_data['push'] = $push;
362 } elseif (in_array($type, ['as:Add'])) {
364 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
365 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
366 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
367 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
368 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
369 $object_data['push'] = $push;
372 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
373 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
374 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
375 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
376 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
377 $object_data['push'] = $push;
379 // An Undo is done on the object of an object, so we need that type as well
380 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
381 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
385 $object_data = self::addActivityFields($object_data, $activity);
387 if (empty($object_data['object_type'])) {
388 $object_data['object_type'] = $object_type;
391 $object_data['type'] = $type;
392 $object_data['actor'] = $actor;
393 $object_data['item_receiver'] = $receivers;
394 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
395 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
397 $author = $object_data['author'] ?? $actor;
398 if (!empty($author) && !empty($object_data['id'])) {
399 $author_host = parse_url($author, PHP_URL_HOST);
400 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
401 if ($author_host == $id_host) {
402 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
404 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
405 $trust_source = false;
409 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
415 * Fetches the first user id from the receiver array
417 * @param array $receivers Array with receivers
418 * @return integer user id;
420 public static function getFirstUserFromReceivers($receivers)
422 foreach ($receivers as $receiver) {
423 if (!empty($receiver)) {
431 * Processes the activity object
433 * @param array $activity Array with activity data
434 * @param string $body
435 * @param integer $uid User ID
436 * @param boolean $trust_source Do we trust the source?
437 * @param boolean $push Message had been pushed to our system
440 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
442 $type = JsonLD::fetchElement($activity, '@type');
444 Logger::info('Empty type', ['activity' => $activity]);
448 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
449 Logger::info('Empty object', ['activity' => $activity]);
453 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
455 Logger::info('Empty actor', ['activity' => $activity]);
459 if (is_array($activity['as:object'])) {
460 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
465 // Test the provided signatures against the actor and "attributedTo"
467 if (!empty($attributed_to) && !empty($actor)) {
468 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
470 $trust_source = in_array($actor, $signer);
474 // $trust_source is called by reference and is set to true if the content was retrieved successfully
475 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
476 if (empty($object_data)) {
477 Logger::info('No object data found', ['activity' => $activity]);
481 if (!$trust_source) {
482 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
486 if (!empty($body) && empty($object_data['raw'])) {
487 $object_data['raw'] = $body;
490 // Internal flag for thread completion. See Processor.php
491 if (!empty($activity['thread-completion'])) {
492 $object_data['thread-completion'] = $activity['thread-completion'];
495 // Internal flag for posts that arrived via relay
496 if (!empty($activity['from-relay'])) {
497 $object_data['from-relay'] = $activity['from-relay'];
502 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
503 $item = ActivityPub\Processor::createItem($object_data);
504 ActivityPub\Processor::postItem($object_data, $item);
509 if ($object_data['object_type'] == 'as:tag') {
510 ActivityPub\Processor::addTag($object_data);
515 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
516 $object_data['thread-completion'] = Contact::getIdForURL($actor);
518 $item = ActivityPub\Processor::createItem($object_data);
523 $item['post-type'] = Item::PT_ANNOUNCEMENT;
524 ActivityPub\Processor::postItem($object_data, $item);
526 $announce_object_data = self::processObject($activity);
527 $announce_object_data['name'] = $type;
528 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
529 $announce_object_data['object_id'] = $object_data['object_id'];
530 $announce_object_data['object_type'] = $object_data['object_type'];
531 $announce_object_data['push'] = $push;
534 $announce_object_data['raw'] = $body;
537 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
542 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
543 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
548 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
549 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
553 case 'as:TentativeAccept':
554 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
555 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
560 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
561 ActivityPub\Processor::updateItem($object_data);
562 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
563 ActivityPub\Processor::updatePerson($object_data);
568 if ($object_data['object_type'] == 'as:Tombstone') {
569 ActivityPub\Processor::deleteItem($object_data);
570 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
571 ActivityPub\Processor::deletePerson($object_data);
576 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
577 ActivityPub\Processor::followUser($object_data);
578 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
579 $object_data['reply-to-id'] = $object_data['object_id'];
580 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
585 if ($object_data['object_type'] == 'as:Follow') {
586 ActivityPub\Processor::acceptFollowUser($object_data);
587 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
588 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
593 if ($object_data['object_type'] == 'as:Follow') {
594 ActivityPub\Processor::rejectFollowUser($object_data);
595 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
596 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
601 if (($object_data['object_type'] == 'as:Follow') &&
602 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
603 ActivityPub\Processor::undoFollowUser($object_data);
604 } elseif (($object_data['object_type'] == 'as:Accept') &&
605 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
606 ActivityPub\Processor::rejectFollowUser($object_data);
607 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
608 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
609 ActivityPub\Processor::undoActivity($object_data);
614 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
620 * Fetch the receiver list from an activity array
622 * @param array $activity
623 * @param string $actor
625 * @param boolean $fetch_unlisted
627 * @return array with receivers (user id)
630 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
632 $reply = $receivers = [];
634 // When it is an answer, we inherite the receivers from the parent
635 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
636 if (!empty($replyto)) {
639 // Fix possibly wrong item URI (could be an answer to a plink uri)
640 $fixedReplyTo = Item::getURIByLink($replyto);
641 if (!empty($fixedReplyTo)) {
642 $reply[] = $fixedReplyTo;
646 // Fetch all posts that refer to the object id
647 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
648 if (!empty($object_id)) {
649 $reply[] = $object_id;
652 if (!empty($reply)) {
653 $parents = Item::select(['uid'], ['uri' => $reply]);
654 while ($parent = Item::fetch($parents)) {
655 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
659 if (!empty($actor)) {
660 $profile = APContact::getByURL($actor);
661 $followers = $profile['followers'] ?? '';
663 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
665 Logger::info('Empty actor', ['activity' => $activity]);
669 // We have to prevent false follower assumptions upon thread completions
670 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
672 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
673 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
674 if (empty($receiver_list)) {
678 foreach ($receiver_list as $receiver) {
679 if ($receiver == self::PUBLIC_COLLECTION) {
680 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
683 // Add receiver "-1" for unlisted posts
684 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
685 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
688 // Fetch the receivers for the public and the followers collection
689 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
690 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
694 // Fetching all directly addressed receivers
695 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
696 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
697 if (!DBA::isResult($contact)) {
701 // Check if the potential receiver is following the actor
702 // Exception: The receiver is targetted via "to" or this is a comment
703 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
704 $networks = Protocol::FEDERATED;
705 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
706 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
708 // Forum posts are only accepted from forum contacts
709 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
710 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
713 if (!DBA::exists('contact', $condition)) {
718 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
719 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
722 $type = self::TARGET_TO;
725 $type = self::TARGET_CC;
728 $type = self::TARGET_BTO;
731 $type = self::TARGET_BCC;
735 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
740 self::switchContacts($receivers, $actor);
746 * Fetch the receiver list of a given actor
748 * @param string $actor
750 * @param array $receivers
751 * @param integer $target_type
753 * @return array with receivers (user id)
756 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
758 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
759 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
761 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
762 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
763 while ($contact = DBA::fetch($contacts)) {
764 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
765 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
768 DBA::close($contacts);
770 // The queries are split because of performance issues
771 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
772 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
773 while ($contact = DBA::fetch($contacts)) {
774 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
775 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
778 DBA::close($contacts);
783 * Tests if the contact is a valid receiver for this actor
785 * @param array $contact
786 * @param string $actor
789 * @return bool with receivers (user id)
792 private static function isValidReceiverForActor($contact, $tags)
794 // Are we following the contact? Then this is a valid receiver
795 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
799 // When the possible receiver isn't a community, then it is no valid receiver
800 $owner = User::getOwnerDataById($contact['uid']);
801 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
805 // Is the community account tagged?
806 foreach ($tags as $tag) {
807 if ($tag['type'] != 'Mention') {
811 if (Strings::compareLink($tag['href'], $owner['url'])) {
820 * Switches existing contacts to ActivityPub
822 * @param integer $cid Contact ID
823 * @param integer $uid User ID
824 * @param string $url Profile URL
825 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
826 * @throws \ImagickException
828 public static function switchContact($cid, $uid, $url)
830 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
831 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
835 if (Contact::updateFromProbe($cid)) {
836 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
839 // Send a new follow request to be sure that the connection still exists
840 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
841 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
842 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
851 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
852 * @throws \ImagickException
854 private static function switchContacts($receivers, $actor)
860 foreach ($receivers as $receiver) {
861 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
862 if (DBA::isResult($contact)) {
863 self::switchContact($contact['id'], $receiver['uid'], $actor);
866 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
867 if (DBA::isResult($contact)) {
868 self::switchContact($contact['id'], $receiver['uid'], $actor);
876 * @param $object_data
877 * @param array $activity
881 private static function addActivityFields($object_data, $activity)
883 if (!empty($activity['published']) && empty($object_data['published'])) {
884 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
887 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
888 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
891 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
892 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
894 if (!empty($object_data['object_id'])) {
895 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
896 $objectId = Item::getURIByLink($object_data['object_id']);
897 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
898 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
899 $object_data['object_id'] = $objectId;
907 * Fetches the object data from external ressources if needed
909 * @param string $object_id Object ID of the the provided object
910 * @param array $object The provided object array
911 * @param boolean $trust_source Do we trust the provided object?
912 * @param integer $uid User ID for the signature that we use to fetch data
914 * @return array|false with trusted and valid object data
915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916 * @throws \ImagickException
918 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
920 // By fetching the type we check if the object is complete.
921 $type = JsonLD::fetchElement($object, '@type');
923 if (!$trust_source || empty($type)) {
924 $data = ActivityPub::fetchContent($object_id, $uid);
926 $object = JsonLD::compact($data);
927 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
929 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
931 $item = Item::selectFirst([], ['uri' => $object_id]);
932 if (!DBA::isResult($item)) {
933 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
936 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
937 $data = ActivityPub\Transmitter::createNote($item);
938 $object = JsonLD::compact($data);
941 $id = JsonLD::fetchElement($object, '@id');
943 Logger::info('Empty id');
947 if ($id != $object_id) {
948 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
952 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
955 $type = JsonLD::fetchElement($object, '@type');
957 Logger::info('Empty type');
961 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
962 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
963 $object_data = self::processObject($object);
966 $object_data['raw'] = json_encode($data);
971 if ($type == 'as:Announce') {
972 $object_id = JsonLD::fetchElement($object, 'object', '@id');
973 if (empty($object_id) || !is_string($object_id)) {
976 return self::fetchObject($object_id, [], false, $uid);
979 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
984 * Convert tags from JSON-LD format into a simplified format
986 * @param array $tags Tags in JSON-LD format
988 * @return array with tags in a simplified format
990 public static function processTags(array $tags)
994 foreach ($tags as $tag) {
999 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1000 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1001 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1003 if (empty($element['type'])) {
1007 if (empty($element['href'])) {
1008 $element['href'] = $element['name'];
1011 $taglist[] = $element;
1017 * Convert emojis from JSON-LD format into a simplified format
1019 * @param array $emojis
1020 * @return array with emojis in a simplified format
1022 private static function processEmojis(array $emojis)
1026 foreach ($emojis as $emoji) {
1027 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1031 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1032 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1035 $emojilist[] = $element;
1042 * Convert attachments from JSON-LD format into a simplified format
1044 * @param array $attachments Attachments in JSON-LD format
1046 * @return array Attachments in a simplified format
1048 private static function processAttachments(array $attachments)
1052 // Removes empty values
1053 $attachments = array_filter($attachments);
1055 foreach ($attachments as $attachment) {
1056 switch (JsonLD::fetchElement($attachment, '@type')) {
1061 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1062 foreach ($urls as $url) {
1063 // Single scalar URL case
1064 if (is_string($url)) {
1069 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1070 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1071 if (Strings::startsWith($mediaType, 'image')) {
1080 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1081 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1083 'image' => $pageImage,
1088 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1089 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1090 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1091 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
1095 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1096 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1097 $imagePreviewUrl = null;
1099 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1100 $imageVariants = [];
1101 $previewVariants = [];
1102 foreach ($urls as $url) {
1103 // Scalar URL, no discrimination possible
1104 if (is_string($url)) {
1105 $imageFullUrl = $url;
1109 // Not sure what to do with a different Link media type than the base Image, we skip
1110 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1114 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1116 // Default URL choice if no discriminating width is provided
1117 $imageFullUrl = $href ?? $imageFullUrl;
1119 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1121 if ($href && $width) {
1122 $imageVariants[$width] = $href;
1123 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1124 $previewVariants[abs(632 - $width)] = $href;
1128 if ($imageVariants) {
1129 // Taking the maximum size image
1130 ksort($imageVariants);
1131 $imageFullUrl = array_pop($imageVariants);
1133 // Taking the minimum number distance to the target distance
1134 ksort($previewVariants);
1135 $imagePreviewUrl = array_shift($previewVariants);
1138 unset($imageVariants);
1139 unset($previewVariants);
1143 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1144 'mediaType' => $mediaType,
1145 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1146 'url' => $imageFullUrl,
1147 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1152 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1153 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1154 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1155 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1164 * Fetch the original source or content with the "language" Markdown or HTML
1166 * @param array $object
1167 * @param array $object_data
1170 * @throws \Exception
1172 private static function getSource($object, $object_data)
1174 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1175 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1176 if (!empty($object_data['source'])) {
1177 return $object_data;
1180 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1181 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1182 if (!empty($object_data['source'])) {
1183 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1184 return $object_data;
1187 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1188 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1189 if (!empty($object_data['source'])) {
1190 $object_data['source'] = HTML::toBBCode($object_data['source']);
1191 return $object_data;
1194 return $object_data;
1198 * Check if the "as:url" element is an array with multiple links
1199 * This is the case with audio and video posts.
1200 * Then the links are added as attachments
1202 * @param array $object The raw object
1203 * @param array $object_data The parsed object data for later processing
1204 * @return array the object data
1206 private static function processAttachmentUrls(array $object, array $object_data) {
1207 // Check if this is some url with multiple links
1208 if (empty($object['as:url'])) {
1209 return $object_data;
1212 $urls = $object['as:url'];
1213 $keys = array_keys($urls);
1214 if (!is_numeric(array_pop($keys))) {
1215 return $object_data;
1220 foreach ($urls as $url) {
1221 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1225 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1230 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1231 if (empty($mediatype)) {
1235 if ($mediatype == 'text/html') {
1236 $object_data['alternate-url'] = $href;
1239 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1241 if ($filetype == 'audio') {
1242 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => null, 'size' => null];
1243 } elseif ($filetype == 'video') {
1244 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1245 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1247 // We save bandwidth by using a moderate height (alt least 480 pixel height)
1248 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1249 if (!empty($attachments[$filetype]['height']) &&
1250 ($height > $attachments[$filetype]['height']) && ($attachments[$filetype]['height'] >= 480)) {
1254 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size];
1255 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1256 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1258 // For Torrent links we always store the highest resolution
1259 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1263 $attachments[$mediatype] = ['type' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null];
1267 foreach ($attachments as $type => $attachment) {
1268 $object_data['attachments'][] = ['type' => $type,
1269 'mediaType' => $attachment['type'],
1270 'height' => $attachment['height'],
1271 'size' => $attachment['size'],
1273 'url' => $attachment['url']];
1275 return $object_data;
1279 * Fetches data from the object part of an activity
1281 * @param array $object
1284 * @throws \Exception
1286 private static function processObject($object)
1288 if (!JsonLD::fetchElement($object, '@id')) {
1293 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1294 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1295 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1297 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1298 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1299 $object_data['reply-to-id'] = $object_data['id'];
1301 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1302 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1303 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1304 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1305 $object_data['reply-to-id'] = $replyToId;
1309 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1310 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1312 if (empty($object_data['updated'])) {
1313 $object_data['updated'] = $object_data['published'];
1316 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1317 $object_data['published'] = $object_data['updated'];
1320 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1321 if (empty($actor)) {
1322 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1325 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1326 $location = JsonLD::fetchElement($location, 'location', '@value');
1328 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1329 // down to HTML and then finally format to plaintext.
1330 $location = Markdown::convert($location);
1331 $location = BBCode::convert($location);
1332 $location = HTML::toPlaintext($location);
1335 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1336 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1337 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1338 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1339 $object_data['actor'] = $object_data['author'] = $actor;
1340 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1341 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1342 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1343 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1344 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1345 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1346 $object_data = self::getSource($object, $object_data);
1347 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1348 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1349 $object_data['location'] = $location;
1350 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1351 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1352 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1353 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1354 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1355 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1356 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1357 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1358 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1359 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1361 // Special treatment for Hubzilla links
1362 if (is_array($object_data['alternate-url'])) {
1363 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1365 if (!is_string($object_data['alternate-url'])) {
1366 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1370 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1371 $object_data = self::processAttachmentUrls($object, $object_data);
1374 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1375 $receivers = $reception_types = [];
1376 foreach ($receiverdata as $key => $data) {
1377 $receivers[$key] = $data['uid'];
1378 $reception_types[$data['uid']] = $data['type'] ?? 0;
1381 $object_data['receiver'] = $receivers;
1382 $object_data['reception_type'] = $reception_types;
1384 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1385 unset($object_data['receiver'][-1]);
1386 unset($object_data['reception_type'][-1]);
1388 // Common object data:
1391 // @context, type, actor, signature, mediaType, duration, replies, icon
1393 // Also missing: (Defined in the standard, but currently unused)
1394 // audience, preview, endTime, startTime, image
1399 // contentMap, announcement_count, announcements, context_id, likes, like_count
1400 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1405 // category, licence, language, commentsEnabled
1408 // views, waitTranscoding, state, support, subtitleLanguage
1409 // likes, dislikes, shares, comments
1411 return $object_data;