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\Conversation;
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'];
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);
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
179 * @param integer $uid User ID
180 * @param $trust_source
182 * @return array with object data
183 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
184 * @throws \ImagickException
186 private static function prepareObjectData($activity, $uid, &$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);
234 $object_data['object_id'] = $object_id;
236 // Test if it is an answer to a mail
237 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
238 $object_data['directmessage'] = true;
240 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
243 // We had been able to retrieve the object data - so we can trust the source
244 $trust_source = true;
245 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
246 // Create a mostly empty array out of the activity data (instead of the object).
247 // This way we later don't have to check for the existence of ech individual array element.
248 $object_data = self::processObject($activity);
249 $object_data['name'] = $type;
250 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
251 $object_data['object_id'] = $object_id;
252 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
253 } elseif (in_array($type, ['as:Add'])) {
255 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
256 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
257 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
258 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
259 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
262 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
263 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
264 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
265 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
266 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
268 // An Undo is done on the object of an object, so we need that type as well
269 if ($type == 'as:Undo') {
270 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
274 $object_data = self::addActivityFields($object_data, $activity);
276 if (empty($object_data['object_type'])) {
277 $object_data['object_type'] = $object_type;
280 $object_data['type'] = $type;
281 $object_data['actor'] = $actor;
282 $object_data['item_receiver'] = $receivers;
283 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
285 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
291 * Fetches the first user id from the receiver array
293 * @param array $receivers Array with receivers
294 * @return integer user id;
296 public static function getFirstUserFromReceivers($receivers)
298 foreach ($receivers as $receiver) {
299 if (!empty($receiver)) {
307 * Store the unprocessed data into the conversation table
308 * This has to be done outside the regular function,
309 * since we store everything - not only item posts.
311 * @param array $activity Array with activity data
312 * @param string $body The raw message
315 private static function storeConversation($activity, $body)
317 if (empty($body) || empty($activity['id'])) {
322 'protocol' => Conversation::PARCEL_ACTIVITYPUB,
323 'item-uri' => $activity['id'],
324 'reply-to-uri' => $activity['reply-to-id'] ?? '',
325 'conversation-href' => $activity['context'] ?? '',
326 'conversation-uri' => $activity['conversation'] ?? '',
328 'received' => DateTimeFormat::utcNow()];
330 DBA::insert('conversation', $conversation, true);
334 * Processes the activity object
336 * @param array $activity Array with activity data
337 * @param string $body
338 * @param integer $uid User ID
339 * @param boolean $trust_source Do we trust the source?
342 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
344 $type = JsonLD::fetchElement($activity, '@type');
346 Logger::log('Empty type', Logger::DEBUG);
350 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
351 Logger::log('Empty object', Logger::DEBUG);
355 if (!JsonLD::fetchElement($activity, 'as:actor', '@id')) {
356 Logger::log('Empty actor', Logger::DEBUG);
361 // Don't trust the source if "actor" differs from "attributedTo". The content could be forged.
362 if ($trust_source && ($type == 'as:Create') && is_array($activity['as:object'])) {
363 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
364 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
365 $trust_source = ($actor == $attributed_to);
366 if (!$trust_source) {
367 Logger::log('Not trusting actor: ' . $actor . '. It differs from attributedTo: ' . $attributed_to, Logger::DEBUG);
371 // $trust_source is called by reference and is set to true if the content was retrieved successfully
372 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
373 if (empty($object_data)) {
374 Logger::log('No object data found', Logger::DEBUG);
378 if (!$trust_source) {
379 Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
383 // Only store content related stuff - and no announces, since they possibly overwrite the original content
384 if (in_array($object_data['object_type'], self::CONTENT_TYPES) && ($type != 'as:Announce')) {
385 self::storeConversation($object_data, $body);
388 // Internal flag for thread completion. See Processor.php
389 if (!empty($activity['thread-completion'])) {
390 $object_data['thread-completion'] = $activity['thread-completion'];
395 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
396 ActivityPub\Processor::createItem($object_data);
401 if ($object_data['object_type'] == 'as:tag') {
402 ActivityPub\Processor::addTag($object_data);
407 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
408 $profile = APContact::getByURL($object_data['actor']);
409 // Reshared posts from persons appear as summary at the bottom
410 // If this isn't set, then a single reshare appears on top. This is used for groups.
411 $object_data['thread-completion'] = ($profile['type'] != 'Group');
413 ActivityPub\Processor::createItem($object_data);
415 // Add the bottom reshare information only for persons
416 if ($profile['type'] != 'Group') {
417 $announce_object_data = self::processObject($activity);
418 $announce_object_data['name'] = $type;
419 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
420 $announce_object_data['object_id'] = $object_data['object_id'];
421 $announce_object_data['object_type'] = $object_data['object_type'];
423 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
429 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
430 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
435 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
436 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
440 case 'as:TentativeAccept':
441 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
442 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
447 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
448 ActivityPub\Processor::updateItem($object_data);
449 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
450 ActivityPub\Processor::updatePerson($object_data);
455 if ($object_data['object_type'] == 'as:Tombstone') {
456 ActivityPub\Processor::deleteItem($object_data);
457 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
458 ActivityPub\Processor::deletePerson($object_data);
463 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
464 ActivityPub\Processor::followUser($object_data);
465 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
466 $object_data['reply-to-id'] = $object_data['object_id'];
467 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
472 if ($object_data['object_type'] == 'as:Follow') {
473 ActivityPub\Processor::acceptFollowUser($object_data);
474 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
475 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
480 if ($object_data['object_type'] == 'as:Follow') {
481 ActivityPub\Processor::rejectFollowUser($object_data);
482 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
483 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
488 if (($object_data['object_type'] == 'as:Follow') &&
489 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
490 ActivityPub\Processor::undoFollowUser($object_data);
491 } elseif (($object_data['object_type'] == 'as:Accept') &&
492 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
493 ActivityPub\Processor::rejectFollowUser($object_data);
494 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
495 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
496 ActivityPub\Processor::undoActivity($object_data);
501 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
507 * Fetch the receiver list from an activity array
509 * @param array $activity
510 * @param string $actor
513 * @return array with receivers (user id)
516 private static function getReceivers($activity, $actor, $tags = [])
520 // When it is an answer, we inherite the receivers from the parent
521 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
522 if (!empty($replyto)) {
523 // Fix possibly wrong item URI (could be an answer to a plink uri)
524 $fixedReplyTo = Item::getURIByLink($replyto);
525 $replyto = $fixedReplyTo ?: $replyto;
527 $parents = Item::select(['uid'], ['uri' => $replyto]);
528 while ($parent = Item::fetch($parents)) {
529 $receivers['uid:' . $parent['uid']] = $parent['uid'];
533 if (!empty($actor)) {
534 $profile = APContact::getByURL($actor);
535 $followers = $profile['followers'] ?? '';
537 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
539 Logger::log('Empty actor', Logger::DEBUG);
543 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
544 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
545 if (empty($receiver_list)) {
549 foreach ($receiver_list as $receiver) {
550 if ($receiver == self::PUBLIC_COLLECTION) {
551 $receivers['uid:0'] = 0;
554 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
555 // This will most likely catch all OStatus connections to Mastodon
556 $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
557 , 'archive' => false, 'pending' => false];
558 $contacts = DBA::select('contact', ['uid'], $condition);
559 while ($contact = DBA::fetch($contacts)) {
560 if ($contact['uid'] != 0) {
561 $receivers['uid:' . $contact['uid']] = $contact['uid'];
564 DBA::close($contacts);
567 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
568 $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
572 // Fetching all directly addressed receivers
573 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
574 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
575 if (!DBA::isResult($contact)) {
579 // Check if the potential receiver is following the actor
580 // Exception: The receiver is targetted via "to" or this is a comment
581 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
582 $networks = Protocol::FEDERATED;
583 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
584 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
586 // Forum posts are only accepted from forum contacts
587 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
588 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
591 if (!DBA::exists('contact', $condition)) {
596 $receivers['uid:' . $contact['uid']] = $contact['uid'];
600 self::switchContacts($receivers, $actor);
606 * Fetch the receiver list of a given actor
608 * @param string $actor
611 * @return array with receivers (user id)
614 public static function getReceiverForActor($actor, $tags)
617 $networks = Protocol::FEDERATED;
618 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
619 'network' => $networks, 'archive' => false, 'pending' => false];
620 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
621 while ($contact = DBA::fetch($contacts)) {
622 if (self::isValidReceiverForActor($contact, $actor, $tags)) {
623 $receivers['uid:' . $contact['uid']] = $contact['uid'];
626 DBA::close($contacts);
631 * Tests if the contact is a valid receiver for this actor
633 * @param array $contact
634 * @param string $actor
637 * @return bool with receivers (user id)
640 private static function isValidReceiverForActor($contact, $actor, $tags)
642 // Public contacts are no valid receiver
643 if ($contact['uid'] == 0) {
647 // Are we following the contact? Then this is a valid receiver
648 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
652 // When the possible receiver isn't a community, then it is no valid receiver
653 $owner = User::getOwnerDataById($contact['uid']);
654 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
658 // Is the community account tagged?
659 foreach ($tags as $tag) {
660 if ($tag['type'] != 'Mention') {
664 if ($tag['href'] == $owner['url']) {
673 * Switches existing contacts to ActivityPub
675 * @param integer $cid Contact ID
676 * @param integer $uid User ID
677 * @param string $url Profile URL
678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679 * @throws \ImagickException
681 public static function switchContact($cid, $uid, $url)
683 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
684 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
688 if (Contact::updateFromProbe($cid, '', true)) {
689 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
692 // Send a new follow request to be sure that the connection still exists
693 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
694 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
695 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
705 * @throws \ImagickException
707 private static function switchContacts($receivers, $actor)
713 foreach ($receivers as $receiver) {
714 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
715 if (DBA::isResult($contact)) {
716 self::switchContact($contact['id'], $receiver, $actor);
719 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
720 if (DBA::isResult($contact)) {
721 self::switchContact($contact['id'], $receiver, $actor);
729 * @param $object_data
730 * @param array $activity
734 private static function addActivityFields($object_data, $activity)
736 if (!empty($activity['published']) && empty($object_data['published'])) {
737 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
740 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
741 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
744 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
745 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
747 if (!empty($object_data['object_id'])) {
748 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
749 $objectId = Item::getURIByLink($object_data['object_id']);
750 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
751 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
752 $object_data['object_id'] = $objectId;
760 * Fetches the object data from external ressources if needed
762 * @param string $object_id Object ID of the the provided object
763 * @param array $object The provided object array
764 * @param boolean $trust_source Do we trust the provided object?
765 * @param integer $uid User ID for the signature that we use to fetch data
767 * @return array|false with trusted and valid object data
768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
769 * @throws \ImagickException
771 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
773 // By fetching the type we check if the object is complete.
774 $type = JsonLD::fetchElement($object, '@type');
776 if (!$trust_source || empty($type)) {
777 $data = ActivityPub::fetchContent($object_id, $uid);
779 $object = JsonLD::compact($data);
780 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
782 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
784 $item = Item::selectFirst([], ['uri' => $object_id]);
785 if (!DBA::isResult($item)) {
786 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
789 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
790 $data = ActivityPub\Transmitter::createNote($item);
791 $object = JsonLD::compact($data);
794 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
797 $type = JsonLD::fetchElement($object, '@type');
800 Logger::log('Empty type', Logger::DEBUG);
804 if (in_array($type, self::CONTENT_TYPES)) {
805 return self::processObject($object);
808 if ($type == 'as:Announce') {
809 $object_id = JsonLD::fetchElement($object, 'object', '@id');
810 if (empty($object_id) || !is_string($object_id)) {
813 return self::fetchObject($object_id, [], false, $uid);
816 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
821 * Convert tags from JSON-LD format into a simplified format
823 * @param array $tags Tags in JSON-LD format
825 * @return array with tags in a simplified format
827 private static function processTags($tags)
835 foreach ($tags as $tag) {
840 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
841 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
842 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
844 if (empty($element['type'])) {
848 $taglist[] = $element;
854 * Convert emojis from JSON-LD format into a simplified format
857 * @return array with emojis in a simplified format
859 private static function processEmojis($emojis)
863 if (empty($emojis)) {
867 foreach ($emojis as $emoji) {
868 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
872 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
873 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
876 $emojilist[] = $element;
882 * Convert attachments from JSON-LD format into a simplified format
884 * @param array $attachments Attachments in JSON-LD format
886 * @return array with attachmants in a simplified format
888 private static function processAttachments($attachments)
892 if (empty($attachments)) {
896 foreach ($attachments as $attachment) {
897 if (empty($attachment)) {
901 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
902 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
903 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
904 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')];
910 * Fetch the original source or content with the "language" Markdown or HTML
912 * @param array $object
913 * @param array $object_data
918 private static function getSource($object, $object_data)
920 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
921 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
922 if (!empty($object_data['source'])) {
926 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
927 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
928 if (!empty($object_data['source'])) {
929 $object_data['source'] = Markdown::toBBCode($object_data['source']);
933 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
934 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
935 if (!empty($object_data['source'])) {
936 $object_data['source'] = HTML::toBBCode($object_data['source']);
944 * Fetches data from the object part of an activity
946 * @param array $object
951 private static function processObject($object)
953 if (!JsonLD::fetchElement($object, '@id')) {
958 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
959 $object_data['id'] = JsonLD::fetchElement($object, '@id');
960 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
962 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
963 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
964 $object_data['reply-to-id'] = $object_data['id'];
966 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
967 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
968 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
969 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
970 $object_data['reply-to-id'] = $replyToId;
974 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
975 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
977 if (empty($object_data['updated'])) {
978 $object_data['updated'] = $object_data['published'];
981 if (empty($object_data['published']) && !empty($object_data['updated'])) {
982 $object_data['published'] = $object_data['updated'];
985 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
987 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
990 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
991 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
992 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
993 $object_data['actor'] = $object_data['author'] = $actor;
994 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
995 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
996 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
997 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
998 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
999 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1000 $object_data = self::getSource($object, $object_data);
1001 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1002 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1003 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1004 $object_data['location'] = JsonLD::fetchElement($object_data, 'location', '@value');
1005 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1006 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1007 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1008 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1009 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
1010 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
1011 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
1012 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1013 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1014 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1016 // Special treatment for Hubzilla links
1017 if (is_array($object_data['alternate-url'])) {
1018 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1020 if (!is_string($object_data['alternate-url'])) {
1021 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1025 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']);
1027 // Common object data:
1030 // @context, type, actor, signature, mediaType, duration, replies, icon
1032 // Also missing: (Defined in the standard, but currently unused)
1033 // audience, preview, endTime, startTime, image
1038 // contentMap, announcement_count, announcements, context_id, likes, like_count
1039 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1044 // category, licence, language, commentsEnabled
1047 // views, waitTranscoding, state, support, subtitleLanguage
1048 // likes, dislikes, shares, comments
1050 return $object_data;