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;
65 const TARGET_FOLLOWER = 4;
68 * Checks if the web request is done for the AP protocol
70 * @return bool is it AP?
72 public static function isRequest()
74 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
75 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
79 * Checks incoming message from the inbox
83 * @param integer $uid User ID
86 public static function processInbox($body, $header, $uid)
88 $http_signer = HTTPSignature::getSigner($body, $header);
89 if (empty($http_signer)) {
90 Logger::warning('Invalid HTTP signature, message will be discarded.');
93 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
96 $signer = [$http_signer];
97 $activity = json_decode($body, true);
99 if (empty($activity)) {
100 Logger::warning('Invalid body.');
104 $ldactivity = JsonLD::compact($activity);
106 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
108 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
110 if (LDSignature::isSigned($activity)) {
111 $ld_signer = LDSignature::getSigner($activity);
112 if (empty($ld_signer)) {
113 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
114 } elseif ($ld_signer != $http_signer) {
115 $signer[] = $ld_signer;
117 if (!empty($ld_signer && ($actor == $http_signer))) {
118 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
119 $trust_source = true;
120 } elseif (!empty($ld_signer)) {
121 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
122 $trust_source = true;
123 } elseif ($actor == $http_signer) {
124 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
125 $trust_source = true;
127 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
128 $trust_source = false;
130 } elseif ($actor == $http_signer) {
131 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
132 $trust_source = true;
134 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
135 $trust_source = false;
138 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
142 * Fetches the object type for a given object id
144 * @param array $activity
145 * @param string $object_id Object ID of the the provided object
146 * @param integer $uid User ID
148 * @return string with object type
149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
150 * @throws \ImagickException
152 private static function fetchObjectType($activity, $object_id, $uid = 0)
154 if (!empty($activity['as:object'])) {
155 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
156 if (!empty($object_type)) {
161 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
162 // We just assume "note" since it doesn't make a difference for the further processing
166 $profile = APContact::getByURL($object_id);
167 if (!empty($profile['type'])) {
168 return 'as:' . $profile['type'];
171 $data = ActivityPub::fetchContent($object_id, $uid);
173 $object = JsonLD::compact($data);
174 $type = JsonLD::fetchElement($object, '@type');
184 * Prepare the object array
186 * @param array $activity Array with activity data
187 * @param integer $uid User ID
188 * @param boolean $push Message had been pushed to our system
189 * @param boolean $trust_source Do we trust the source?
191 * @return array with object data
192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
193 * @throws \ImagickException
195 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
197 $id = JsonLD::fetchElement($activity, '@id');
198 if (!empty($id) && !$trust_source) {
199 $fetched_activity = ActivityPub::fetchContent($id, $uid ?? 0);
200 if (!empty($fetched_activity)) {
201 $object = JsonLD::compact($fetched_activity);
202 $fetched_id = JsonLD::fetchElement($object, '@id');
203 if ($fetched_id == $id) {
204 Logger::info('Activity had been fetched successfully', ['id' => $id]);
205 $trust_source = true;
208 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
211 Logger::info('Activity could not been fetched', ['id' => $id]);
215 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
217 Logger::info('Empty actor', ['activity' => $activity]);
221 $type = JsonLD::fetchElement($activity, '@type');
223 // Fetch all receivers from to, cc, bto and bcc
224 $receivers = self::getReceivers($activity, $actor);
225 $reception_type = [];
227 // When it is a delivery to a personal inbox we add that user to the receivers
229 $reception_type[$uid] = self::TARGET_BCC;
230 $additional = ['uid:' . $uid => $uid];
231 $receivers = array_merge($receivers, $additional);
233 // We possibly need some user to fetch private content,
234 // so we fetch the first out ot the list.
235 $uid = self::getFirstUserFromReceivers($receivers);
238 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
239 if (empty($object_id)) {
240 Logger::log('No object found', Logger::DEBUG);
244 if (!is_string($object_id)) {
245 Logger::info('Invalid object id', ['object' => $object_id]);
249 $object_type = self::fetchObjectType($activity, $object_id, $uid);
251 // Fetch the content only on activities where this matters
252 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
253 // Always fetch on "Announce"
254 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $uid);
255 if (empty($object_data)) {
256 Logger::log("Object data couldn't be processed", Logger::DEBUG);
260 $object_data['object_id'] = $object_id;
262 if ($type == 'as:Announce') {
263 $object_data['push'] = false;
265 $object_data['push'] = $push;
268 // Test if it is an answer to a mail
269 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
270 $object_data['directmessage'] = true;
272 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
274 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
275 // Create a mostly empty array out of the activity data (instead of the object).
276 // This way we later don't have to check for the existence of ech individual array element.
277 $object_data = self::processObject($activity);
278 $object_data['name'] = $type;
279 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
280 $object_data['object_id'] = $object_id;
281 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
282 } elseif (in_array($type, ['as:Add'])) {
284 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
285 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
286 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
287 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
288 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
291 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
292 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
293 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
294 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
295 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
297 // An Undo is done on the object of an object, so we need that type as well
298 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
299 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
303 $object_data = self::addActivityFields($object_data, $activity);
305 if (empty($object_data['object_type'])) {
306 $object_data['object_type'] = $object_type;
309 $object_data['type'] = $type;
310 $object_data['actor'] = $actor;
311 $object_data['item_receiver'] = $receivers;
312 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
313 $object_data['reception_type'] = $reception_type;
315 $author = $object_data['author'] ?? $actor;
316 if (!empty($author) && !empty($object_data['id'])) {
317 $author_host = parse_url($author, PHP_URL_HOST);
318 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
319 if ($author_host == $id_host) {
320 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
322 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
323 $trust_source = false;
327 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
333 * Fetches the first user id from the receiver array
335 * @param array $receivers Array with receivers
336 * @return integer user id;
338 public static function getFirstUserFromReceivers($receivers)
340 foreach ($receivers as $receiver) {
341 if (!empty($receiver)) {
349 * Processes the activity object
351 * @param array $activity Array with activity data
352 * @param string $body
353 * @param integer $uid User ID
354 * @param boolean $trust_source Do we trust the source?
355 * @param boolean $push Message had been pushed to our system
358 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
360 $type = JsonLD::fetchElement($activity, '@type');
362 Logger::info('Empty type', ['activity' => $activity]);
366 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
367 Logger::info('Empty object', ['activity' => $activity]);
371 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
373 Logger::info('Empty actor', ['activity' => $activity]);
377 if (is_array($activity['as:object'])) {
378 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
383 // Test the provided signatures against the actor and "attributedTo"
385 if (!empty($attributed_to) && !empty($actor)) {
386 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
388 $trust_source = in_array($actor, $signer);
392 // $trust_source is called by reference and is set to true if the content was retrieved successfully
393 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
394 if (empty($object_data)) {
395 Logger::info('No object data found', ['activity' => $activity]);
399 if (!$trust_source) {
400 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
404 if (!empty($body) && empty($object_data['raw'])) {
405 $object_data['raw'] = $body;
408 // Internal flag for thread completion. See Processor.php
409 if (!empty($activity['thread-completion'])) {
410 $object_data['thread-completion'] = $activity['thread-completion'];
415 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
416 $item = ActivityPub\Processor::createItem($object_data);
417 ActivityPub\Processor::postItem($object_data, $item);
422 if ($object_data['object_type'] == 'as:tag') {
423 ActivityPub\Processor::addTag($object_data);
428 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
429 $object_data['thread-completion'] = true;
431 $item = ActivityPub\Processor::createItem($object_data);
432 ActivityPub\Processor::postItem($object_data, $item);
434 $announce_object_data = self::processObject($activity);
435 $announce_object_data['name'] = $type;
436 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
437 $announce_object_data['object_id'] = $object_data['object_id'];
438 $announce_object_data['object_type'] = $object_data['object_type'];
439 $announce_object_data['push'] = $push;
442 $announce_object_data['raw'] = $body;
445 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
450 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
451 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
456 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
457 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
461 case 'as:TentativeAccept':
462 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
463 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
468 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
469 ActivityPub\Processor::updateItem($object_data);
470 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
471 ActivityPub\Processor::updatePerson($object_data);
476 if ($object_data['object_type'] == 'as:Tombstone') {
477 ActivityPub\Processor::deleteItem($object_data);
478 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
479 ActivityPub\Processor::deletePerson($object_data);
484 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
485 ActivityPub\Processor::followUser($object_data);
486 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
487 $object_data['reply-to-id'] = $object_data['object_id'];
488 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
493 if ($object_data['object_type'] == 'as:Follow') {
494 ActivityPub\Processor::acceptFollowUser($object_data);
495 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
496 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
501 if ($object_data['object_type'] == 'as:Follow') {
502 ActivityPub\Processor::rejectFollowUser($object_data);
503 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
504 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
509 if (($object_data['object_type'] == 'as:Follow') &&
510 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
511 ActivityPub\Processor::undoFollowUser($object_data);
512 } elseif (($object_data['object_type'] == 'as:Accept') &&
513 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
514 ActivityPub\Processor::rejectFollowUser($object_data);
515 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
516 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
517 ActivityPub\Processor::undoActivity($object_data);
522 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
528 * Fetch the receiver list from an activity array
530 * @param array $activity
531 * @param string $actor
533 * @param boolean $fetch_unlisted
535 * @return array with receivers (user id)
538 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
542 // When it is an answer, we inherite the receivers from the parent
543 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
544 if (!empty($replyto)) {
545 // Fix possibly wrong item URI (could be an answer to a plink uri)
546 $fixedReplyTo = Item::getURIByLink($replyto);
547 $replyto = $fixedReplyTo ?: $replyto;
549 $parents = Item::select(['uid'], ['uri' => $replyto]);
550 while ($parent = Item::fetch($parents)) {
551 $receivers['uid:' . $parent['uid']] = $parent['uid'];
555 if (!empty($actor)) {
556 $profile = APContact::getByURL($actor);
557 $followers = $profile['followers'] ?? '';
559 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
561 Logger::info('Empty actor', ['activity' => $activity]);
565 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
566 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
567 if (empty($receiver_list)) {
571 foreach ($receiver_list as $receiver) {
572 if ($receiver == self::PUBLIC_COLLECTION) {
573 $receivers['uid:0'] = 0;
576 // Add receiver "-1" for unlisted posts
577 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
578 $receivers['uid:-1'] = -1;
581 // Fetch the receivers for the public and the followers collection
582 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
583 $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
587 // Fetching all directly addressed receivers
588 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
589 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
590 if (!DBA::isResult($contact)) {
594 // Check if the potential receiver is following the actor
595 // Exception: The receiver is targetted via "to" or this is a comment
596 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
597 $networks = Protocol::FEDERATED;
598 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
599 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
601 // Forum posts are only accepted from forum contacts
602 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
603 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
606 if (!DBA::exists('contact', $condition)) {
611 $receivers['uid:' . $contact['uid']] = $contact['uid'];
615 self::switchContacts($receivers, $actor);
621 * Fetch the receiver list of a given actor
623 * @param string $actor
626 * @return array with receivers (user id)
629 private static function getReceiverForActor($actor, $tags)
632 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
633 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
635 $condition = DBA::mergeConditions($basecondition, ['nurl' => Strings::normaliseLink($actor)]);
636 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
637 while ($contact = DBA::fetch($contacts)) {
638 if (self::isValidReceiverForActor($contact, $actor, $tags)) {
639 $receivers['uid:' . $contact['uid']] = $contact['uid'];
642 DBA::close($contacts);
644 // The queries are split because of performance issues
645 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?)", Strings::normaliseLink($actor), $actor]);
646 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
647 while ($contact = DBA::fetch($contacts)) {
648 if (self::isValidReceiverForActor($contact, $actor, $tags)) {
649 $receivers['uid:' . $contact['uid']] = $contact['uid'];
652 DBA::close($contacts);
657 * Tests if the contact is a valid receiver for this actor
659 * @param array $contact
660 * @param string $actor
663 * @return bool with receivers (user id)
666 private static function isValidReceiverForActor($contact, $actor, $tags)
668 // Public contacts are no valid receiver
669 if ($contact['uid'] == 0) {
673 // Are we following the contact? Then this is a valid receiver
674 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
678 // When the possible receiver isn't a community, then it is no valid receiver
679 $owner = User::getOwnerDataById($contact['uid']);
680 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
684 // Is the community account tagged?
685 foreach ($tags as $tag) {
686 if ($tag['type'] != 'Mention') {
690 if ($tag['href'] == $owner['url']) {
699 * Switches existing contacts to ActivityPub
701 * @param integer $cid Contact ID
702 * @param integer $uid User ID
703 * @param string $url Profile URL
704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
705 * @throws \ImagickException
707 public static function switchContact($cid, $uid, $url)
709 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
710 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
714 if (Contact::updateFromProbe($cid)) {
715 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
718 // Send a new follow request to be sure that the connection still exists
719 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
720 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
721 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
730 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
731 * @throws \ImagickException
733 private static function switchContacts($receivers, $actor)
739 foreach ($receivers as $receiver) {
740 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
741 if (DBA::isResult($contact)) {
742 self::switchContact($contact['id'], $receiver, $actor);
745 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
746 if (DBA::isResult($contact)) {
747 self::switchContact($contact['id'], $receiver, $actor);
755 * @param $object_data
756 * @param array $activity
760 private static function addActivityFields($object_data, $activity)
762 if (!empty($activity['published']) && empty($object_data['published'])) {
763 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
766 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
767 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
770 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
771 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
773 if (!empty($object_data['object_id'])) {
774 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
775 $objectId = Item::getURIByLink($object_data['object_id']);
776 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
777 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
778 $object_data['object_id'] = $objectId;
786 * Fetches the object data from external ressources if needed
788 * @param string $object_id Object ID of the the provided object
789 * @param array $object The provided object array
790 * @param boolean $trust_source Do we trust the provided object?
791 * @param integer $uid User ID for the signature that we use to fetch data
793 * @return array|false with trusted and valid object data
794 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
795 * @throws \ImagickException
797 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
799 // By fetching the type we check if the object is complete.
800 $type = JsonLD::fetchElement($object, '@type');
802 if (!$trust_source || empty($type)) {
803 $data = ActivityPub::fetchContent($object_id, $uid);
805 $object = JsonLD::compact($data);
806 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
808 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
810 $item = Item::selectFirst([], ['uri' => $object_id]);
811 if (!DBA::isResult($item)) {
812 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
815 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
816 $data = ActivityPub\Transmitter::createNote($item);
817 $object = JsonLD::compact($data);
820 $id = JsonLD::fetchElement($object, '@id');
822 Logger::info('Empty id');
826 if ($id != $object_id) {
827 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
831 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
834 $type = JsonLD::fetchElement($object, '@type');
836 Logger::info('Empty type');
840 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
841 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
842 $object_data = self::processObject($object);
845 $object_data['raw'] = json_encode($data);
850 if ($type == 'as:Announce') {
851 $object_id = JsonLD::fetchElement($object, 'object', '@id');
852 if (empty($object_id) || !is_string($object_id)) {
855 return self::fetchObject($object_id, [], false, $uid);
858 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
863 * Convert tags from JSON-LD format into a simplified format
865 * @param array $tags Tags in JSON-LD format
867 * @return array with tags in a simplified format
869 private static function processTags(array $tags)
873 foreach ($tags as $tag) {
878 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
879 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
880 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
882 if (empty($element['type'])) {
886 if (empty($element['href'])) {
887 $element['href'] = $element['name'];
890 $taglist[] = $element;
896 * Convert emojis from JSON-LD format into a simplified format
898 * @param array $emojis
899 * @return array with emojis in a simplified format
901 private static function processEmojis(array $emojis)
905 foreach ($emojis as $emoji) {
906 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
910 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
911 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
914 $emojilist[] = $element;
921 * Convert attachments from JSON-LD format into a simplified format
923 * @param array $attachments Attachments in JSON-LD format
925 * @return array Attachments in a simplified format
927 private static function processAttachments(array $attachments)
931 // Removes empty values
932 $attachments = array_filter($attachments);
934 foreach ($attachments as $attachment) {
935 switch (JsonLD::fetchElement($attachment, '@type')) {
940 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
941 foreach ($urls as $url) {
942 // Single scalar URL case
943 if (is_string($url)) {
948 $href = JsonLD::fetchElement($url, 'as:href', '@id');
949 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
950 if (Strings::startsWith($mediaType, 'image')) {
959 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
960 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
962 'image' => $pageImage,
967 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
968 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
969 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
970 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
974 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
975 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
976 $imagePreviewUrl = null;
978 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
980 $previewVariants = [];
981 foreach ($urls as $url) {
982 // Scalar URL, no discrimination possible
983 if (is_string($url)) {
984 $imageFullUrl = $url;
988 // Not sure what to do with a different Link media type than the base Image, we skip
989 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
993 $href = JsonLD::fetchElement($url, 'as:href', '@id');
995 // Default URL choice if no discriminating width is provided
996 $imageFullUrl = $href ?? $imageFullUrl;
998 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1000 if ($href && $width) {
1001 $imageVariants[$width] = $href;
1002 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1003 $previewVariants[abs(632 - $width)] = $href;
1007 if ($imageVariants) {
1008 // Taking the maximum size image
1009 ksort($imageVariants);
1010 $imageFullUrl = array_pop($imageVariants);
1012 // Taking the minimum number distance to the target distance
1013 ksort($previewVariants);
1014 $imagePreviewUrl = array_shift($previewVariants);
1017 unset($imageVariants);
1018 unset($previewVariants);
1022 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1023 'mediaType' => $mediaType,
1024 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1025 'url' => $imageFullUrl,
1026 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1031 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1032 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1033 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1034 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1043 * Fetch the original source or content with the "language" Markdown or HTML
1045 * @param array $object
1046 * @param array $object_data
1049 * @throws \Exception
1051 private static function getSource($object, $object_data)
1053 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1054 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1055 if (!empty($object_data['source'])) {
1056 return $object_data;
1059 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1060 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1061 if (!empty($object_data['source'])) {
1062 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1063 return $object_data;
1066 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1067 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1068 if (!empty($object_data['source'])) {
1069 $object_data['source'] = HTML::toBBCode($object_data['source']);
1070 return $object_data;
1073 return $object_data;
1077 * Check if the "as:url" element is an array with multiple links
1078 * This is the case with audio and video posts.
1079 * Then the links are added as attachments
1081 * @param array $object The raw object
1082 * @param array $object_data The parsed object data for later processing
1083 * @return array the object data
1085 private static function processAttachmentUrls(array $object, array $object_data) {
1086 // Check if this is some url with multiple links
1087 if (empty($object['as:url'])) {
1088 return $object_data;
1091 $urls = $object['as:url'];
1092 $keys = array_keys($urls);
1093 if (!is_numeric(array_pop($keys))) {
1094 return $object_data;
1099 foreach ($urls as $url) {
1100 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1104 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1109 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1110 if (empty($mediatype)) {
1114 if ($mediatype == 'text/html') {
1115 $object_data['alternate-url'] = $href;
1118 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1120 if ($filetype == 'audio') {
1121 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1122 } elseif ($filetype == 'video') {
1123 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1125 // We save bandwidth by using a moderate height
1126 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1127 if (!empty($attachments[$filetype]['height']) &&
1128 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1132 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1136 foreach ($attachments as $type => $attachment) {
1137 $object_data['attachments'][] = ['type' => $type,
1138 'mediaType' => $attachment['type'],
1140 'url' => $attachment['url']];
1142 return $object_data;
1146 * Fetches data from the object part of an activity
1148 * @param array $object
1151 * @throws \Exception
1153 private static function processObject($object)
1155 if (!JsonLD::fetchElement($object, '@id')) {
1160 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1161 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1162 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1164 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1165 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1166 $object_data['reply-to-id'] = $object_data['id'];
1168 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1169 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1170 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1171 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1172 $object_data['reply-to-id'] = $replyToId;
1176 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1177 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1179 if (empty($object_data['updated'])) {
1180 $object_data['updated'] = $object_data['published'];
1183 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1184 $object_data['published'] = $object_data['updated'];
1187 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1188 if (empty($actor)) {
1189 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1192 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1193 $location = JsonLD::fetchElement($location, 'location', '@value');
1195 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1196 // down to HTML and then finally format to plaintext.
1197 $location = Markdown::convert($location);
1198 $location = BBCode::convert($location);
1199 $location = HTML::toPlaintext($location);
1202 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1203 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1204 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1205 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1206 $object_data['actor'] = $object_data['author'] = $actor;
1207 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1208 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1209 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1210 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1211 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1212 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1213 $object_data = self::getSource($object, $object_data);
1214 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1215 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1216 $object_data['location'] = $location;
1217 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1218 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1219 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1220 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1221 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1222 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1223 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1224 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1225 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1226 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1228 // Special treatment for Hubzilla links
1229 if (is_array($object_data['alternate-url'])) {
1230 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1232 if (!is_string($object_data['alternate-url'])) {
1233 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1237 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1238 $object_data = self::processAttachmentUrls($object, $object_data);
1241 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1242 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1243 unset($object_data['receiver']['uid:-1']);
1245 // Common object data:
1248 // @context, type, actor, signature, mediaType, duration, replies, icon
1250 // Also missing: (Defined in the standard, but currently unused)
1251 // audience, preview, endTime, startTime, image
1256 // contentMap, announcement_count, announcements, context_id, likes, like_count
1257 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1262 // category, licence, language, commentsEnabled
1265 // views, waitTranscoding, state, support, subtitleLanguage
1266 // likes, dislikes, shares, comments
1268 return $object_data;