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\DateTimeFormat;
37 use Friendica\Util\HTTPSignature;
38 use Friendica\Util\JsonLD;
39 use Friendica\Util\LDSignature;
40 use Friendica\Util\Strings;
43 * ActivityPub Receiver Protocol class
48 * Check what this is meant to do:
57 const PUBLIC_COLLECTION = 'as:Public';
58 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
59 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio'];
60 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
63 * Checks if the web request is done for the AP protocol
65 * @return bool is it AP?
67 public static function isRequest()
69 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
70 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
74 * Checks incoming message from the inbox
78 * @param integer $uid User ID
81 public static function processInbox($body, $header, $uid)
83 $http_signer = HTTPSignature::getSigner($body, $header);
84 if (empty($http_signer)) {
85 Logger::warning('Invalid HTTP signature, message will be discarded.');
88 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
91 $activity = json_decode($body, true);
93 if (empty($activity)) {
94 Logger::warning('Invalid body.');
98 $ldactivity = JsonLD::compact($activity);
100 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
102 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
104 if (LDSignature::isSigned($activity)) {
105 $ld_signer = LDSignature::getSigner($activity);
106 if (empty($ld_signer)) {
107 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
109 if (!empty($ld_signer && ($actor == $http_signer))) {
110 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
111 $trust_source = true;
112 } elseif (!empty($ld_signer)) {
113 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
114 $trust_source = true;
115 } elseif ($actor == $http_signer) {
116 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
117 $trust_source = true;
119 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
120 $trust_source = false;
122 } elseif ($actor == $http_signer) {
123 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
124 $trust_source = true;
126 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
127 $trust_source = false;
130 self::processActivity($ldactivity, $body, $uid, $trust_source, true);
134 * Fetches the object type for a given object id
136 * @param array $activity
137 * @param string $object_id Object ID of the the provided object
138 * @param integer $uid User ID
140 * @return string with object type
141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
142 * @throws \ImagickException
144 private static function fetchObjectType($activity, $object_id, $uid = 0)
146 if (!empty($activity['as:object'])) {
147 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
148 if (!empty($object_type)) {
153 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
154 // We just assume "note" since it doesn't make a difference for the further processing
158 $profile = APContact::getByURL($object_id);
159 if (!empty($profile['type'])) {
160 return 'as:' . $profile['type'];
163 $data = ActivityPub::fetchContent($object_id, $uid);
165 $object = JsonLD::compact($data);
166 $type = JsonLD::fetchElement($object, '@type');
176 * Prepare the object array
178 * @param array $activity Array with activity data
179 * @param integer $uid User ID
180 * @param boolean $push Message had been pushed to our system
181 * @param boolean $trust_source Do we trust the source?
183 * @return array with object data
184 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
185 * @throws \ImagickException
187 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
189 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
191 Logger::log('Empty actor', Logger::DEBUG);
195 $type = JsonLD::fetchElement($activity, '@type');
197 // Fetch all receivers from to, cc, bto and bcc
198 $receivers = self::getReceivers($activity, $actor);
200 // When it is a delivery to a personal inbox we add that user to the receivers
202 $additional = ['uid:' . $uid => $uid];
203 $receivers = array_merge($receivers, $additional);
205 // We possibly need some user to fetch private content,
206 // so we fetch the first out ot the list.
207 $uid = self::getFirstUserFromReceivers($receivers);
210 Logger::log('Receivers: ' . $uid . ' - ' . json_encode($receivers), Logger::DEBUG);
212 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
213 if (empty($object_id)) {
214 Logger::log('No object found', Logger::DEBUG);
218 if (!is_string($object_id)) {
219 Logger::info('Invalid object id', ['object' => $object_id]);
223 $object_type = self::fetchObjectType($activity, $object_id, $uid);
225 // Fetch the content only on activities where this matters
226 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
227 if ($type == 'as:Announce') {
228 $trust_source = false;
231 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $uid);
232 if (empty($object_data)) {
233 Logger::log("Object data couldn't be processed", Logger::DEBUG);
237 $object_data['object_id'] = $object_id;
239 if ($type == 'as:Announce') {
240 $object_data['push'] = false;
242 $object_data['push'] = $push;
245 // Test if it is an answer to a mail
246 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
247 $object_data['directmessage'] = true;
249 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
252 // We had been able to retrieve the object data - so we can trust the source
253 $trust_source = true;
254 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
255 // Create a mostly empty array out of the activity data (instead of the object).
256 // This way we later don't have to check for the existence of ech individual array element.
257 $object_data = self::processObject($activity);
258 $object_data['name'] = $type;
259 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
260 $object_data['object_id'] = $object_id;
261 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
262 } elseif (in_array($type, ['as:Add'])) {
264 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
265 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
266 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
267 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
268 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
271 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
272 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
273 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
274 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
275 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
277 // An Undo is done on the object of an object, so we need that type as well
278 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
279 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
283 $object_data = self::addActivityFields($object_data, $activity);
285 if (empty($object_data['object_type'])) {
286 $object_data['object_type'] = $object_type;
289 $object_data['type'] = $type;
290 $object_data['actor'] = $actor;
291 $object_data['item_receiver'] = $receivers;
292 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
294 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
300 * Fetches the first user id from the receiver array
302 * @param array $receivers Array with receivers
303 * @return integer user id;
305 public static function getFirstUserFromReceivers($receivers)
307 foreach ($receivers as $receiver) {
308 if (!empty($receiver)) {
316 * Processes the activity object
318 * @param array $activity Array with activity data
319 * @param string $body
320 * @param integer $uid User ID
321 * @param boolean $trust_source Do we trust the source?
322 * @param boolean $push Message had been pushed to our system
325 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false, $push = false)
327 $type = JsonLD::fetchElement($activity, '@type');
329 Logger::log('Empty type', Logger::DEBUG);
333 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
334 Logger::log('Empty object', Logger::DEBUG);
338 if (!JsonLD::fetchElement($activity, 'as:actor', '@id')) {
339 Logger::log('Empty actor', Logger::DEBUG);
343 // Don't trust the source if "actor" differs from "attributedTo". The content could be forged.
344 if ($trust_source && ($type == 'as:Create') && is_array($activity['as:object'])) {
345 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
346 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
347 $trust_source = ($actor == $attributed_to);
348 if (!$trust_source) {
349 Logger::log('Not trusting actor: ' . $actor . '. It differs from attributedTo: ' . $attributed_to, Logger::DEBUG);
353 // $trust_source is called by reference and is set to true if the content was retrieved successfully
354 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
355 if (empty($object_data)) {
356 Logger::log('No object data found', Logger::DEBUG);
360 if (!$trust_source) {
361 Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
365 if (!empty($body) && empty($object_data['raw'])) {
366 $object_data['raw'] = $body;
369 // Internal flag for thread completion. See Processor.php
370 if (!empty($activity['thread-completion'])) {
371 $object_data['thread-completion'] = $activity['thread-completion'];
376 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
377 $item = ActivityPub\Processor::createItem($object_data);
378 ActivityPub\Processor::postItem($object_data, $item);
383 if ($object_data['object_type'] == 'as:tag') {
384 ActivityPub\Processor::addTag($object_data);
389 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
390 $profile = APContact::getByURL($object_data['actor']);
391 // Reshared posts from persons appear as summary at the bottom
392 // If this isn't set, then a single reshare appears on top. This is used for groups.
393 $object_data['thread-completion'] = ($profile['type'] != 'Group');
395 $item = ActivityPub\Processor::createItem($object_data);
396 ActivityPub\Processor::postItem($object_data, $item);
398 // Add the bottom reshare information only for persons
399 if ($profile['type'] != 'Group') {
400 $announce_object_data = self::processObject($activity);
401 $announce_object_data['name'] = $type;
402 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
403 $announce_object_data['object_id'] = $object_data['object_id'];
404 $announce_object_data['object_type'] = $object_data['object_type'];
405 $announce_object_data['push'] = $push;
408 $announce_object_data['raw'] = $body;
411 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
417 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
418 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
423 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
424 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
428 case 'as:TentativeAccept':
429 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
430 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
435 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
436 ActivityPub\Processor::updateItem($object_data);
437 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
438 ActivityPub\Processor::updatePerson($object_data);
443 if ($object_data['object_type'] == 'as:Tombstone') {
444 ActivityPub\Processor::deleteItem($object_data);
445 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
446 ActivityPub\Processor::deletePerson($object_data);
451 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
452 ActivityPub\Processor::followUser($object_data);
453 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
454 $object_data['reply-to-id'] = $object_data['object_id'];
455 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
460 if ($object_data['object_type'] == 'as:Follow') {
461 ActivityPub\Processor::acceptFollowUser($object_data);
462 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
463 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
468 if ($object_data['object_type'] == 'as:Follow') {
469 ActivityPub\Processor::rejectFollowUser($object_data);
470 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
471 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
476 if (($object_data['object_type'] == 'as:Follow') &&
477 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
478 ActivityPub\Processor::undoFollowUser($object_data);
479 } elseif (($object_data['object_type'] == 'as:Accept') &&
480 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
481 ActivityPub\Processor::rejectFollowUser($object_data);
482 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
483 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
484 ActivityPub\Processor::undoActivity($object_data);
489 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
495 * Fetch the receiver list from an activity array
497 * @param array $activity
498 * @param string $actor
500 * @param boolean $fetch_unlisted
502 * @return array with receivers (user id)
505 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
509 // When it is an answer, we inherite the receivers from the parent
510 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
511 if (!empty($replyto)) {
512 // Fix possibly wrong item URI (could be an answer to a plink uri)
513 $fixedReplyTo = Item::getURIByLink($replyto);
514 $replyto = $fixedReplyTo ?: $replyto;
516 $parents = Item::select(['uid'], ['uri' => $replyto]);
517 while ($parent = Item::fetch($parents)) {
518 $receivers['uid:' . $parent['uid']] = $parent['uid'];
522 if (!empty($actor)) {
523 $profile = APContact::getByURL($actor);
524 $followers = $profile['followers'] ?? '';
526 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
528 Logger::log('Empty actor', Logger::DEBUG);
532 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
533 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
534 if (empty($receiver_list)) {
538 foreach ($receiver_list as $receiver) {
539 if ($receiver == self::PUBLIC_COLLECTION) {
540 $receivers['uid:0'] = 0;
543 // Add receiver "-1" for unlisted posts
544 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
545 $receivers['uid:-1'] = -1;
548 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
549 // This will most likely catch all OStatus connections to Mastodon
550 $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
551 , 'archive' => false, 'pending' => false];
552 $contacts = DBA::select('contact', ['uid'], $condition);
553 while ($contact = DBA::fetch($contacts)) {
554 if ($contact['uid'] != 0) {
555 $receivers['uid:' . $contact['uid']] = $contact['uid'];
558 DBA::close($contacts);
561 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
562 $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
566 // Fetching all directly addressed receivers
567 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
568 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
569 if (!DBA::isResult($contact)) {
573 // Check if the potential receiver is following the actor
574 // Exception: The receiver is targetted via "to" or this is a comment
575 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
576 $networks = Protocol::FEDERATED;
577 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
578 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
580 // Forum posts are only accepted from forum contacts
581 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
582 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
585 if (!DBA::exists('contact', $condition)) {
590 $receivers['uid:' . $contact['uid']] = $contact['uid'];
594 self::switchContacts($receivers, $actor);
600 * Fetch the receiver list of a given actor
602 * @param string $actor
605 * @return array with receivers (user id)
608 public static function getReceiverForActor($actor, $tags)
611 $networks = Protocol::FEDERATED;
612 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
613 'network' => $networks, 'archive' => false, 'pending' => false];
614 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
615 while ($contact = DBA::fetch($contacts)) {
616 if (self::isValidReceiverForActor($contact, $actor, $tags)) {
617 $receivers['uid:' . $contact['uid']] = $contact['uid'];
620 DBA::close($contacts);
625 * Tests if the contact is a valid receiver for this actor
627 * @param array $contact
628 * @param string $actor
631 * @return bool with receivers (user id)
634 private static function isValidReceiverForActor($contact, $actor, $tags)
636 // Public contacts are no valid receiver
637 if ($contact['uid'] == 0) {
641 // Are we following the contact? Then this is a valid receiver
642 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
646 // When the possible receiver isn't a community, then it is no valid receiver
647 $owner = User::getOwnerDataById($contact['uid']);
648 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
652 // Is the community account tagged?
653 foreach ($tags as $tag) {
654 if ($tag['type'] != 'Mention') {
658 if ($tag['href'] == $owner['url']) {
667 * Switches existing contacts to ActivityPub
669 * @param integer $cid Contact ID
670 * @param integer $uid User ID
671 * @param string $url Profile URL
672 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
673 * @throws \ImagickException
675 public static function switchContact($cid, $uid, $url)
677 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
678 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
682 if (Contact::updateFromProbe($cid, '', true)) {
683 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
686 // Send a new follow request to be sure that the connection still exists
687 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
688 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
689 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
698 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
699 * @throws \ImagickException
701 private static function switchContacts($receivers, $actor)
707 foreach ($receivers as $receiver) {
708 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
709 if (DBA::isResult($contact)) {
710 self::switchContact($contact['id'], $receiver, $actor);
713 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
714 if (DBA::isResult($contact)) {
715 self::switchContact($contact['id'], $receiver, $actor);
723 * @param $object_data
724 * @param array $activity
728 private static function addActivityFields($object_data, $activity)
730 if (!empty($activity['published']) && empty($object_data['published'])) {
731 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
734 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
735 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
738 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
739 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
741 if (!empty($object_data['object_id'])) {
742 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
743 $objectId = Item::getURIByLink($object_data['object_id']);
744 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
745 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
746 $object_data['object_id'] = $objectId;
754 * Fetches the object data from external ressources if needed
756 * @param string $object_id Object ID of the the provided object
757 * @param array $object The provided object array
758 * @param boolean $trust_source Do we trust the provided object?
759 * @param integer $uid User ID for the signature that we use to fetch data
761 * @return array|false with trusted and valid object data
762 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
763 * @throws \ImagickException
765 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
767 // By fetching the type we check if the object is complete.
768 $type = JsonLD::fetchElement($object, '@type');
770 if (!$trust_source || empty($type)) {
771 $data = ActivityPub::fetchContent($object_id, $uid);
773 $object = JsonLD::compact($data);
774 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
776 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
778 $item = Item::selectFirst([], ['uri' => $object_id]);
779 if (!DBA::isResult($item)) {
780 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
783 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
784 $data = ActivityPub\Transmitter::createNote($item);
785 $object = JsonLD::compact($data);
788 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
791 $type = JsonLD::fetchElement($object, '@type');
794 Logger::log('Empty type', Logger::DEBUG);
798 if (in_array($type, self::CONTENT_TYPES)) {
799 $object_data = self::processObject($object);
802 $object_data['raw'] = json_encode($data);
807 if ($type == 'as:Announce') {
808 $object_id = JsonLD::fetchElement($object, 'object', '@id');
809 if (empty($object_id) || !is_string($object_id)) {
812 return self::fetchObject($object_id, [], false, $uid);
815 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
820 * Convert tags from JSON-LD format into a simplified format
822 * @param array $tags Tags in JSON-LD format
824 * @return array with tags in a simplified format
826 private static function processTags(array $tags)
830 foreach ($tags as $tag) {
835 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
836 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
837 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
839 if (empty($element['type'])) {
843 if (empty($element['href'])) {
844 $element['href'] = $element['name'];
847 $taglist[] = $element;
853 * Convert emojis from JSON-LD format into a simplified format
855 * @param array $emojis
856 * @return array with emojis in a simplified format
858 private static function processEmojis(array $emojis)
862 foreach ($emojis as $emoji) {
863 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
867 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
868 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
871 $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 Attachments in a simplified format
884 private static function processAttachments(array $attachments)
888 // Removes empty values
889 $attachments = array_filter($attachments);
891 foreach ($attachments as $attachment) {
892 switch (JsonLD::fetchElement($attachment, '@type')) {
897 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
898 foreach ($urls as $url) {
899 // Single scalar URL case
900 if (is_string($url)) {
905 $href = JsonLD::fetchElement($url, 'as:href', '@id');
906 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
907 if (Strings::startsWith($mediaType, 'image')) {
916 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
917 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
919 'image' => $pageImage,
924 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
925 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
926 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
927 'url' => JsonLD::fetchElement($attachment, 'as:href', '@id')
931 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
932 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
933 $imagePreviewUrl = null;
935 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
937 $previewVariants = [];
938 foreach ($urls as $url) {
939 // Scalar URL, no discrimination possible
940 if (is_string($url)) {
941 $imageFullUrl = $url;
945 // Not sure what to do with a different Link media type than the base Image, we skip
946 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
950 $href = JsonLD::fetchElement($url, 'as:href', '@id');
952 // Default URL choice if no discriminating width is provided
953 $imageFullUrl = $href ?? $imageFullUrl;
955 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
957 if ($href && $width) {
958 $imageVariants[$width] = $href;
959 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
960 $previewVariants[abs(632 - $width)] = $href;
964 if ($imageVariants) {
965 // Taking the maximum size image
966 ksort($imageVariants);
967 $imageFullUrl = array_pop($imageVariants);
969 // Taking the minimum number distance to the target distance
970 ksort($previewVariants);
971 $imagePreviewUrl = array_shift($previewVariants);
974 unset($imageVariants);
975 unset($previewVariants);
979 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
980 'mediaType' => $mediaType,
981 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
982 'url' => $imageFullUrl,
983 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
988 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
989 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
990 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
991 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')
1000 * Fetch the original source or content with the "language" Markdown or HTML
1002 * @param array $object
1003 * @param array $object_data
1006 * @throws \Exception
1008 private static function getSource($object, $object_data)
1010 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1011 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1012 if (!empty($object_data['source'])) {
1013 return $object_data;
1016 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1017 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1018 if (!empty($object_data['source'])) {
1019 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1020 return $object_data;
1023 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1024 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1025 if (!empty($object_data['source'])) {
1026 $object_data['source'] = HTML::toBBCode($object_data['source']);
1027 return $object_data;
1030 return $object_data;
1034 * Check if the "as:url" element is an array with multiple links
1035 * This is the case with audio and video posts.
1036 * Then the links are added as attachments
1038 * @param array $object The raw object
1039 * @param array $object_data The parsed object data for later processing
1040 * @return array the object data
1042 private static function processAttachmentUrls(array $object, array $object_data) {
1043 // Check if this is some url with multiple links
1044 if (empty($object['as:url'])) {
1045 return $object_data;
1048 $urls = $object['as:url'];
1049 $keys = array_keys($urls);
1050 if (!is_numeric(array_pop($keys))) {
1051 return $object_data;
1056 foreach ($urls as $url) {
1057 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1061 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1066 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1067 if (empty($mediatype)) {
1071 if ($mediatype == 'text/html') {
1072 $object_data['alternate-url'] = $href;
1075 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1077 if ($filetype == 'audio') {
1078 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href];
1079 } elseif ($filetype == 'video') {
1080 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1082 // We save bandwidth by using a moderate height
1083 // Peertube normally uses these heights: 240, 360, 480, 720, 1080
1084 if (!empty($attachments[$filetype]['height']) &&
1085 (($height > 480) || $height < $attachments[$filetype]['height'])) {
1089 $attachments[$filetype] = ['type' => $mediatype, 'url' => $href, 'height' => $height];
1093 foreach ($attachments as $type => $attachment) {
1094 $object_data['attachments'][] = ['type' => $type,
1095 'mediaType' => $attachment['type'],
1097 'url' => $attachment['url']];
1099 return $object_data;
1103 * Fetches data from the object part of an activity
1105 * @param array $object
1108 * @throws \Exception
1110 private static function processObject($object)
1112 if (!JsonLD::fetchElement($object, '@id')) {
1117 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1118 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1119 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1121 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1122 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1123 $object_data['reply-to-id'] = $object_data['id'];
1125 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1126 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1127 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1128 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1129 $object_data['reply-to-id'] = $replyToId;
1133 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1134 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1136 if (empty($object_data['updated'])) {
1137 $object_data['updated'] = $object_data['published'];
1140 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1141 $object_data['published'] = $object_data['updated'];
1144 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1145 if (empty($actor)) {
1146 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1149 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1150 $location = JsonLD::fetchElement($location, 'location', '@value');
1152 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1153 // down to HTML and then finally format to plaintext.
1154 $location = Markdown::convert($location);
1155 $location = BBCode::convert($location);
1156 $location = HTML::toPlaintext($location);
1159 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1160 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1161 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1162 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1163 $object_data['actor'] = $object_data['author'] = $actor;
1164 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1165 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1166 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1167 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1168 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1169 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1170 $object_data = self::getSource($object, $object_data);
1171 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1172 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1173 $object_data['location'] = $location;
1174 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1175 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1176 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1177 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1178 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1179 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1180 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji') ?? []);
1181 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1182 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1183 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1185 // Special treatment for Hubzilla links
1186 if (is_array($object_data['alternate-url'])) {
1187 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1189 if (!is_string($object_data['alternate-url'])) {
1190 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1194 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1195 $object_data = self::processAttachmentUrls($object, $object_data);
1198 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1199 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1200 unset($object_data['receiver']['uid:-1']);
1202 // Common object data:
1205 // @context, type, actor, signature, mediaType, duration, replies, icon
1207 // Also missing: (Defined in the standard, but currently unused)
1208 // audience, preview, endTime, startTime, image
1213 // contentMap, announcement_count, announcements, context_id, likes, like_count
1214 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1219 // category, licence, language, commentsEnabled
1222 // views, waitTranscoding, state, support, subtitleLanguage
1223 // likes, dislikes, shares, comments
1225 return $object_data;