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\Database\DBA;
25 use Friendica\Content\Text\HTML;
26 use Friendica\Content\Text\Markdown;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Model\Contact;
30 use Friendica\Model\APContact;
31 use Friendica\Model\Item;
32 use Friendica\Model\User;
33 use Friendica\Protocol\Activity;
34 use Friendica\Protocol\ActivityPub;
35 use Friendica\Util\DateTimeFormat;
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'];
62 * Checks if the web request is done for the AP protocol
64 * @return bool is it AP?
66 public static function isRequest()
68 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
69 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
73 * Checks incoming message from the inbox
77 * @param integer $uid User ID
80 public static function processInbox($body, $header, $uid)
82 $http_signer = HTTPSignature::getSigner($body, $header);
83 if (empty($http_signer)) {
84 Logger::warning('Invalid HTTP signature, message will be discarded.');
87 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
90 $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 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
103 if (LDSignature::isSigned($activity)) {
104 $ld_signer = LDSignature::getSigner($activity);
105 if (empty($ld_signer)) {
106 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
108 if (!empty($ld_signer && ($actor == $http_signer))) {
109 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
110 $trust_source = true;
111 } elseif (!empty($ld_signer)) {
112 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
113 $trust_source = true;
114 } elseif ($actor == $http_signer) {
115 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
116 $trust_source = true;
118 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
119 $trust_source = false;
121 } elseif ($actor == $http_signer) {
122 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
123 $trust_source = true;
125 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
126 $trust_source = false;
129 self::processActivity($ldactivity, $body, $uid, $trust_source, true);
133 * Fetches the object type for a given object id
135 * @param array $activity
136 * @param string $object_id Object ID of the the provided object
137 * @param integer $uid User ID
139 * @return string with object type
140 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
141 * @throws \ImagickException
143 private static function fetchObjectType($activity, $object_id, $uid = 0)
145 if (!empty($activity['as:object'])) {
146 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
147 if (!empty($object_type)) {
152 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
153 // We just assume "note" since it doesn't make a difference for the further processing
157 $profile = APContact::getByURL($object_id);
158 if (!empty($profile['type'])) {
159 return 'as:' . $profile['type'];
162 $data = ActivityPub::fetchContent($object_id, $uid);
164 $object = JsonLD::compact($data);
165 $type = JsonLD::fetchElement($object, '@type');
175 * Prepare the object array
177 * @param array $activity Array with activity data
178 * @param integer $uid User ID
179 * @param boolean $push Message had been pushed to our system
180 * @param boolean $trust_source Do we trust the source?
182 * @return array with object data
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 private static function prepareObjectData($activity, $uid, $push, &$trust_source)
188 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
190 Logger::log('Empty actor', Logger::DEBUG);
194 $type = JsonLD::fetchElement($activity, '@type');
196 // Fetch all receivers from to, cc, bto and bcc
197 $receivers = self::getReceivers($activity, $actor);
199 // When it is a delivery to a personal inbox we add that user to the receivers
201 $additional = ['uid:' . $uid => $uid];
202 $receivers = array_merge($receivers, $additional);
204 // We possibly need some user to fetch private content,
205 // so we fetch the first out ot the list.
206 $uid = self::getFirstUserFromReceivers($receivers);
209 Logger::log('Receivers: ' . $uid . ' - ' . json_encode($receivers), Logger::DEBUG);
211 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
212 if (empty($object_id)) {
213 Logger::log('No object found', Logger::DEBUG);
217 if (!is_string($object_id)) {
218 Logger::info('Invalid object id', ['object' => $object_id]);
222 $object_type = self::fetchObjectType($activity, $object_id, $uid);
224 // Fetch the content only on activities where this matters
225 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
226 if ($type == 'as:Announce') {
227 $trust_source = false;
229 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $uid);
230 if (empty($object_data)) {
231 Logger::log("Object data couldn't be processed", Logger::DEBUG);
235 $object_data['object_id'] = $object_id;
237 if ($type == 'as:Announce') {
238 $object_data['push'] = false;
240 $object_data['push'] = $push;
243 // Test if it is an answer to a mail
244 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
245 $object_data['directmessage'] = true;
247 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
250 // We had been able to retrieve the object data - so we can trust the source
251 $trust_source = true;
252 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
253 // Create a mostly empty array out of the activity data (instead of the object).
254 // This way we later don't have to check for the existence of ech individual array element.
255 $object_data = self::processObject($activity);
256 $object_data['name'] = $type;
257 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
258 $object_data['object_id'] = $object_id;
259 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
260 } elseif (in_array($type, ['as:Add'])) {
262 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
263 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
264 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
265 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
266 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
269 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
270 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
271 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
272 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
273 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
275 // An Undo is done on the object of an object, so we need that type as well
276 if ($type == 'as:Undo') {
277 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
281 $object_data = self::addActivityFields($object_data, $activity);
283 if (empty($object_data['object_type'])) {
284 $object_data['object_type'] = $object_type;
287 $object_data['type'] = $type;
288 $object_data['actor'] = $actor;
289 $object_data['item_receiver'] = $receivers;
290 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
292 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
298 * Fetches the first user id from the receiver array
300 * @param array $receivers Array with receivers
301 * @return integer user id;
303 public static function getFirstUserFromReceivers($receivers)
305 foreach ($receivers as $receiver) {
306 if (!empty($receiver)) {
314 * Processes the activity object
316 * @param array $activity Array with activity data
317 * @param string $body
318 * @param integer $uid User ID
319 * @param boolean $trust_source Do we trust the source?
320 * @param boolean $push Message had been pushed to our system
323 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false, $push = false)
325 $type = JsonLD::fetchElement($activity, '@type');
327 Logger::log('Empty type', Logger::DEBUG);
331 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
332 Logger::log('Empty object', Logger::DEBUG);
336 if (!JsonLD::fetchElement($activity, 'as:actor', '@id')) {
337 Logger::log('Empty actor', Logger::DEBUG);
342 // Don't trust the source if "actor" differs from "attributedTo". The content could be forged.
343 if ($trust_source && ($type == 'as:Create') && is_array($activity['as:object'])) {
344 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
345 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
346 $trust_source = ($actor == $attributed_to);
347 if (!$trust_source) {
348 Logger::log('Not trusting actor: ' . $actor . '. It differs from attributedTo: ' . $attributed_to, Logger::DEBUG);
352 // $trust_source is called by reference and is set to true if the content was retrieved successfully
353 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
354 if (empty($object_data)) {
355 Logger::log('No object data found', Logger::DEBUG);
359 if (!$trust_source) {
360 Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
364 if (!empty($body) && empty($object_data['raw'])) {
365 $object_data['raw'] = $body;
368 // Internal flag for thread completion. See Processor.php
369 if (!empty($activity['thread-completion'])) {
370 $object_data['thread-completion'] = $activity['thread-completion'];
375 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
376 ActivityPub\Processor::createItem($object_data);
381 if ($object_data['object_type'] == 'as:tag') {
382 ActivityPub\Processor::addTag($object_data);
387 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
388 $profile = APContact::getByURL($object_data['actor']);
389 // Reshared posts from persons appear as summary at the bottom
390 // If this isn't set, then a single reshare appears on top. This is used for groups.
391 $object_data['thread-completion'] = ($profile['type'] != 'Group');
393 ActivityPub\Processor::createItem($object_data);
395 // Add the bottom reshare information only for persons
396 if ($profile['type'] != 'Group') {
397 $announce_object_data = self::processObject($activity);
398 $announce_object_data['name'] = $type;
399 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
400 $announce_object_data['object_id'] = $object_data['object_id'];
401 $announce_object_data['object_type'] = $object_data['object_type'];
402 $announce_object_data['push'] = $push;
405 $announce_object_data['raw'] = $body;
408 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
414 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
415 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
420 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
421 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
425 case 'as:TentativeAccept':
426 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
427 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
432 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
433 ActivityPub\Processor::updateItem($object_data);
434 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
435 ActivityPub\Processor::updatePerson($object_data);
440 if ($object_data['object_type'] == 'as:Tombstone') {
441 ActivityPub\Processor::deleteItem($object_data);
442 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
443 ActivityPub\Processor::deletePerson($object_data);
448 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
449 ActivityPub\Processor::followUser($object_data);
450 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
451 $object_data['reply-to-id'] = $object_data['object_id'];
452 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
457 if ($object_data['object_type'] == 'as:Follow') {
458 ActivityPub\Processor::acceptFollowUser($object_data);
459 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
460 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
465 if ($object_data['object_type'] == 'as:Follow') {
466 ActivityPub\Processor::rejectFollowUser($object_data);
467 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
468 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
473 if (($object_data['object_type'] == 'as:Follow') &&
474 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
475 ActivityPub\Processor::undoFollowUser($object_data);
476 } elseif (($object_data['object_type'] == 'as:Accept') &&
477 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
478 ActivityPub\Processor::rejectFollowUser($object_data);
479 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
480 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
481 ActivityPub\Processor::undoActivity($object_data);
486 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
492 * Fetch the receiver list from an activity array
494 * @param array $activity
495 * @param string $actor
497 * @param boolean $fetch_unlisted
499 * @return array with receivers (user id)
502 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
506 // When it is an answer, we inherite the receivers from the parent
507 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
508 if (!empty($replyto)) {
509 // Fix possibly wrong item URI (could be an answer to a plink uri)
510 $fixedReplyTo = Item::getURIByLink($replyto);
511 $replyto = $fixedReplyTo ?: $replyto;
513 $parents = Item::select(['uid'], ['uri' => $replyto]);
514 while ($parent = Item::fetch($parents)) {
515 $receivers['uid:' . $parent['uid']] = $parent['uid'];
519 if (!empty($actor)) {
520 $profile = APContact::getByURL($actor);
521 $followers = $profile['followers'] ?? '';
523 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
525 Logger::log('Empty actor', Logger::DEBUG);
529 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
530 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
531 if (empty($receiver_list)) {
535 foreach ($receiver_list as $receiver) {
536 if ($receiver == self::PUBLIC_COLLECTION) {
537 $receivers['uid:0'] = 0;
540 // Add receiver "-1" for unlisted posts
541 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
542 $receivers['uid:-1'] = -1;
545 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
546 // This will most likely catch all OStatus connections to Mastodon
547 $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
548 , 'archive' => false, 'pending' => false];
549 $contacts = DBA::select('contact', ['uid'], $condition);
550 while ($contact = DBA::fetch($contacts)) {
551 if ($contact['uid'] != 0) {
552 $receivers['uid:' . $contact['uid']] = $contact['uid'];
555 DBA::close($contacts);
558 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
559 $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
563 // Fetching all directly addressed receivers
564 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
565 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
566 if (!DBA::isResult($contact)) {
570 // Check if the potential receiver is following the actor
571 // Exception: The receiver is targetted via "to" or this is a comment
572 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
573 $networks = Protocol::FEDERATED;
574 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
575 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
577 // Forum posts are only accepted from forum contacts
578 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
579 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
582 if (!DBA::exists('contact', $condition)) {
587 $receivers['uid:' . $contact['uid']] = $contact['uid'];
591 self::switchContacts($receivers, $actor);
597 * Fetch the receiver list of a given actor
599 * @param string $actor
602 * @return array with receivers (user id)
605 public static function getReceiverForActor($actor, $tags)
608 $networks = Protocol::FEDERATED;
609 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
610 'network' => $networks, 'archive' => false, 'pending' => false];
611 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
612 while ($contact = DBA::fetch($contacts)) {
613 if (self::isValidReceiverForActor($contact, $actor, $tags)) {
614 $receivers['uid:' . $contact['uid']] = $contact['uid'];
617 DBA::close($contacts);
622 * Tests if the contact is a valid receiver for this actor
624 * @param array $contact
625 * @param string $actor
628 * @return bool with receivers (user id)
631 private static function isValidReceiverForActor($contact, $actor, $tags)
633 // Public contacts are no valid receiver
634 if ($contact['uid'] == 0) {
638 // Are we following the contact? Then this is a valid receiver
639 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
643 // When the possible receiver isn't a community, then it is no valid receiver
644 $owner = User::getOwnerDataById($contact['uid']);
645 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
649 // Is the community account tagged?
650 foreach ($tags as $tag) {
651 if ($tag['type'] != 'Mention') {
655 if ($tag['href'] == $owner['url']) {
664 * Switches existing contacts to ActivityPub
666 * @param integer $cid Contact ID
667 * @param integer $uid User ID
668 * @param string $url Profile URL
669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670 * @throws \ImagickException
672 public static function switchContact($cid, $uid, $url)
674 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
675 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
679 if (Contact::updateFromProbe($cid, '', true)) {
680 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
683 // Send a new follow request to be sure that the connection still exists
684 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
685 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
686 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
696 * @throws \ImagickException
698 private static function switchContacts($receivers, $actor)
704 foreach ($receivers as $receiver) {
705 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
706 if (DBA::isResult($contact)) {
707 self::switchContact($contact['id'], $receiver, $actor);
710 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
711 if (DBA::isResult($contact)) {
712 self::switchContact($contact['id'], $receiver, $actor);
720 * @param $object_data
721 * @param array $activity
725 private static function addActivityFields($object_data, $activity)
727 if (!empty($activity['published']) && empty($object_data['published'])) {
728 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
731 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
732 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
735 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
736 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
738 if (!empty($object_data['object_id'])) {
739 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
740 $objectId = Item::getURIByLink($object_data['object_id']);
741 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
742 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
743 $object_data['object_id'] = $objectId;
751 * Fetches the object data from external ressources if needed
753 * @param string $object_id Object ID of the the provided object
754 * @param array $object The provided object array
755 * @param boolean $trust_source Do we trust the provided object?
756 * @param integer $uid User ID for the signature that we use to fetch data
758 * @return array|false with trusted and valid object data
759 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
760 * @throws \ImagickException
762 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
764 // By fetching the type we check if the object is complete.
765 $type = JsonLD::fetchElement($object, '@type');
767 if (!$trust_source || empty($type)) {
768 $data = ActivityPub::fetchContent($object_id, $uid);
770 $object = JsonLD::compact($data);
771 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
773 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
775 $item = Item::selectFirst([], ['uri' => $object_id]);
776 if (!DBA::isResult($item)) {
777 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
780 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
781 $data = ActivityPub\Transmitter::createNote($item);
782 $object = JsonLD::compact($data);
785 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
788 $type = JsonLD::fetchElement($object, '@type');
791 Logger::log('Empty type', Logger::DEBUG);
795 if (in_array($type, self::CONTENT_TYPES)) {
796 $object_data = self::processObject($object);
799 $object_data['raw'] = json_encode($data);
804 if ($type == 'as:Announce') {
805 $object_id = JsonLD::fetchElement($object, 'object', '@id');
806 if (empty($object_id) || !is_string($object_id)) {
809 return self::fetchObject($object_id, [], false, $uid);
812 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
817 * Convert tags from JSON-LD format into a simplified format
819 * @param array $tags Tags in JSON-LD format
821 * @return array with tags in a simplified format
823 private static function processTags($tags)
831 foreach ($tags as $tag) {
836 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
837 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
838 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
840 if (empty($element['type'])) {
844 $taglist[] = $element;
850 * Convert emojis from JSON-LD format into a simplified format
853 * @return array with emojis in a simplified format
855 private static function processEmojis($emojis)
859 if (empty($emojis)) {
863 foreach ($emojis as $emoji) {
864 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
868 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
869 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
872 $emojilist[] = $element;
878 * Convert attachments from JSON-LD format into a simplified format
880 * @param array $attachments Attachments in JSON-LD format
882 * @return array with attachmants in a simplified format
884 private static function processAttachments($attachments)
888 if (empty($attachments)) {
892 foreach ($attachments as $attachment) {
893 if (empty($attachment)) {
897 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
898 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
899 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
900 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')];
906 * Fetch the original source or content with the "language" Markdown or HTML
908 * @param array $object
909 * @param array $object_data
914 private static function getSource($object, $object_data)
916 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
917 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
918 if (!empty($object_data['source'])) {
922 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
923 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
924 if (!empty($object_data['source'])) {
925 $object_data['source'] = Markdown::toBBCode($object_data['source']);
929 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
930 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
931 if (!empty($object_data['source'])) {
932 $object_data['source'] = HTML::toBBCode($object_data['source']);
940 * Check if the "as:url" element is an array with multiple links
941 * This is the case with audio and video posts.
942 * Then the links are added as attachments
944 * @param array $object The raw object
945 * @param array $object_data The parsed object data for later processing
946 * @return array the object data
948 private static function processAttachmentUrls(array $object, array $object_data) {
949 // Check if this is some url with multiple links
950 if (empty($object['as:url'])) {
954 $urls = $object['as:url'];
955 $keys = array_keys($urls);
956 if (!is_numeric(array_pop($keys))) {
962 foreach ($urls as $url) {
963 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
967 $href = JsonLD::fetchElement($url, 'as:href', '@id');
972 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
973 if (empty($mediatype)) {
977 if ($mediatype == 'text/html') {
978 $object_data['alternate-url'] = $href;
981 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
983 if ($filetype == 'audio') {
984 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
985 } elseif ($filetype == 'video') {
986 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
988 // We save bandwidth by using a moderate height
989 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
990 if (!empty($attachments[$filetype]['height']) &&
991 (($height > 480) || $height < $attachments[$filetype]['height'])) {
995 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
999 foreach ($attachments as $type => $attachment) {
1000 $object_data['attachments'][] = ['type' => $type,
1001 'mediaType' => $attachment['type'],
1003 'url' => $attachment['url']];
1005 return $object_data;
1009 * Fetches data from the object part of an activity
1011 * @param array $object
1014 * @throws \Exception
1016 private static function processObject($object)
1018 if (!JsonLD::fetchElement($object, '@id')) {
1023 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1024 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1025 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1027 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1028 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1029 $object_data['reply-to-id'] = $object_data['id'];
1031 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1032 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1033 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1034 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1035 $object_data['reply-to-id'] = $replyToId;
1039 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1040 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1042 if (empty($object_data['updated'])) {
1043 $object_data['updated'] = $object_data['published'];
1046 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1047 $object_data['published'] = $object_data['updated'];
1050 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1051 if (empty($actor)) {
1052 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1055 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1056 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1057 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1058 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1059 $object_data['actor'] = $object_data['author'] = $actor;
1060 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1061 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1062 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1063 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1064 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1065 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1066 $object_data = self::getSource($object, $object_data);
1067 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1068 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1069 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1070 $object_data['location'] = JsonLD::fetchElement($object_data, 'location', '@value');
1071 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1072 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1073 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1074 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1075 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
1076 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
1077 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
1078 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1079 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1080 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1082 // Special treatment for Hubzilla links
1083 if (is_array($object_data['alternate-url'])) {
1084 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1086 if (!is_string($object_data['alternate-url'])) {
1087 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1091 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1092 $object_data = self::processAttachmentUrls($object, $object_data);
1095 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1096 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1097 unset($object_data['receiver']['uid:-1']);
1099 // Common object data:
1102 // @context, type, actor, signature, mediaType, duration, replies, icon
1104 // Also missing: (Defined in the standard, but currently unused)
1105 // audience, preview, endTime, startTime, image
1110 // contentMap, announcement_count, announcements, context_id, likes, like_count
1111 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1116 // category, licence, language, commentsEnabled
1119 // views, waitTranscoding, state, support, subtitleLanguage
1120 // likes, dislikes, shares, comments
1122 return $object_data;