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, 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
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, $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;
230 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $uid);
231 if (empty($object_data)) {
232 Logger::log("Object data couldn't be processed", Logger::DEBUG);
236 $object_data['object_id'] = $object_id;
237 $object_data['push'] = $push;
239 // Test if it is an answer to a mail
240 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
241 $object_data['directmessage'] = true;
243 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
246 // We had been able to retrieve the object data - so we can trust the source
247 $trust_source = true;
248 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
249 // Create a mostly empty array out of the activity data (instead of the object).
250 // This way we later don't have to check for the existence of ech individual array element.
251 $object_data = self::processObject($activity);
252 $object_data['name'] = $type;
253 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
254 $object_data['object_id'] = $object_id;
255 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
256 } elseif (in_array($type, ['as:Add'])) {
258 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
259 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
260 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
261 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
262 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
265 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
266 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
267 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
268 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
269 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
271 // An Undo is done on the object of an object, so we need that type as well
272 if ($type == 'as:Undo') {
273 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
277 $object_data = self::addActivityFields($object_data, $activity);
279 if (empty($object_data['object_type'])) {
280 $object_data['object_type'] = $object_type;
283 $object_data['type'] = $type;
284 $object_data['actor'] = $actor;
285 $object_data['item_receiver'] = $receivers;
286 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
288 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
294 * Fetches the first user id from the receiver array
296 * @param array $receivers Array with receivers
297 * @return integer user id;
299 public static function getFirstUserFromReceivers($receivers)
301 foreach ($receivers as $receiver) {
302 if (!empty($receiver)) {
310 * Store the unprocessed data into the conversation table
311 * This has to be done outside the regular function,
312 * since we store everything - not only item posts.
314 * @param array $activity Array with activity data
315 * @param string $body The raw message
318 private static function storeConversation($activity, $body)
320 if (empty($body) || empty($activity['id'])) {
325 'protocol' => Conversation::PARCEL_ACTIVITYPUB,
326 'item-uri' => $activity['id'],
327 'reply-to-uri' => $activity['reply-to-id'] ?? '',
328 'conversation-href' => $activity['context'] ?? '',
329 'conversation-uri' => $activity['conversation'] ?? '',
331 'received' => DateTimeFormat::utcNow()];
333 DBA::insert('conversation', $conversation, true);
337 * Processes the activity object
339 * @param array $activity Array with activity data
340 * @param string $body
341 * @param integer $uid User ID
342 * @param boolean $trust_source Do we trust the source?
345 public static function processActivity($activity, $body = '', $uid = null, $trust_source = false, $push = false)
347 $type = JsonLD::fetchElement($activity, '@type');
349 Logger::log('Empty type', Logger::DEBUG);
353 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
354 Logger::log('Empty object', Logger::DEBUG);
358 if (!JsonLD::fetchElement($activity, 'as:actor', '@id')) {
359 Logger::log('Empty actor', Logger::DEBUG);
364 // Don't trust the source if "actor" differs from "attributedTo". The content could be forged.
365 if ($trust_source && ($type == 'as:Create') && is_array($activity['as:object'])) {
366 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
367 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
368 $trust_source = ($actor == $attributed_to);
369 if (!$trust_source) {
370 Logger::log('Not trusting actor: ' . $actor . '. It differs from attributedTo: ' . $attributed_to, Logger::DEBUG);
374 // $trust_source is called by reference and is set to true if the content was retrieved successfully
375 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
376 if (empty($object_data)) {
377 Logger::log('No object data found', Logger::DEBUG);
381 if (!$trust_source) {
382 Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
386 // Only store content related stuff - and no announces, since they possibly overwrite the original content
387 if (in_array($object_data['object_type'], self::CONTENT_TYPES) && ($type != 'as:Announce')) {
388 self::storeConversation($object_data, $body);
391 // Internal flag for thread completion. See Processor.php
392 if (!empty($activity['thread-completion'])) {
393 $object_data['thread-completion'] = $activity['thread-completion'];
398 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
399 ActivityPub\Processor::createItem($object_data);
404 if ($object_data['object_type'] == 'as:tag') {
405 ActivityPub\Processor::addTag($object_data);
410 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
411 $profile = APContact::getByURL($object_data['actor']);
412 // Reshared posts from persons appear as summary at the bottom
413 // If this isn't set, then a single reshare appears on top. This is used for groups.
414 $object_data['thread-completion'] = ($profile['type'] != 'Group');
416 ActivityPub\Processor::createItem($object_data);
418 // Add the bottom reshare information only for persons
419 if ($profile['type'] != 'Group') {
420 $announce_object_data = self::processObject($activity);
421 $announce_object_data['name'] = $type;
422 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
423 $announce_object_data['object_id'] = $object_data['object_id'];
424 $announce_object_data['object_type'] = $object_data['object_type'];
426 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
432 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
433 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
438 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
439 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
443 case 'as:TentativeAccept':
444 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
445 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
450 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
451 ActivityPub\Processor::updateItem($object_data);
452 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
453 ActivityPub\Processor::updatePerson($object_data);
458 if ($object_data['object_type'] == 'as:Tombstone') {
459 ActivityPub\Processor::deleteItem($object_data);
460 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
461 ActivityPub\Processor::deletePerson($object_data);
466 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
467 ActivityPub\Processor::followUser($object_data);
468 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
469 $object_data['reply-to-id'] = $object_data['object_id'];
470 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
475 if ($object_data['object_type'] == 'as:Follow') {
476 ActivityPub\Processor::acceptFollowUser($object_data);
477 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
478 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
483 if ($object_data['object_type'] == 'as:Follow') {
484 ActivityPub\Processor::rejectFollowUser($object_data);
485 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
486 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
491 if (($object_data['object_type'] == 'as:Follow') &&
492 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
493 ActivityPub\Processor::undoFollowUser($object_data);
494 } elseif (($object_data['object_type'] == 'as:Accept') &&
495 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
496 ActivityPub\Processor::rejectFollowUser($object_data);
497 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
498 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
499 ActivityPub\Processor::undoActivity($object_data);
504 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
510 * Fetch the receiver list from an activity array
512 * @param array $activity
513 * @param string $actor
516 * @return array with receivers (user id)
519 private static function getReceivers($activity, $actor, $tags = [])
523 // When it is an answer, we inherite the receivers from the parent
524 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
525 if (!empty($replyto)) {
526 // Fix possibly wrong item URI (could be an answer to a plink uri)
527 $fixedReplyTo = Item::getURIByLink($replyto);
528 $replyto = $fixedReplyTo ?: $replyto;
530 $parents = Item::select(['uid'], ['uri' => $replyto]);
531 while ($parent = Item::fetch($parents)) {
532 $receivers['uid:' . $parent['uid']] = $parent['uid'];
536 if (!empty($actor)) {
537 $profile = APContact::getByURL($actor);
538 $followers = $profile['followers'] ?? '';
540 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
542 Logger::log('Empty actor', Logger::DEBUG);
546 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
547 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
548 if (empty($receiver_list)) {
552 foreach ($receiver_list as $receiver) {
553 if ($receiver == self::PUBLIC_COLLECTION) {
554 $receivers['uid:0'] = 0;
557 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
558 // This will most likely catch all OStatus connections to Mastodon
559 $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
560 , 'archive' => false, 'pending' => false];
561 $contacts = DBA::select('contact', ['uid'], $condition);
562 while ($contact = DBA::fetch($contacts)) {
563 if ($contact['uid'] != 0) {
564 $receivers['uid:' . $contact['uid']] = $contact['uid'];
567 DBA::close($contacts);
570 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
571 $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
575 // Fetching all directly addressed receivers
576 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
577 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
578 if (!DBA::isResult($contact)) {
582 // Check if the potential receiver is following the actor
583 // Exception: The receiver is targetted via "to" or this is a comment
584 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
585 $networks = Protocol::FEDERATED;
586 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
587 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
589 // Forum posts are only accepted from forum contacts
590 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
591 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
594 if (!DBA::exists('contact', $condition)) {
599 $receivers['uid:' . $contact['uid']] = $contact['uid'];
603 self::switchContacts($receivers, $actor);
609 * Fetch the receiver list of a given actor
611 * @param string $actor
614 * @return array with receivers (user id)
617 public static function getReceiverForActor($actor, $tags)
620 $networks = Protocol::FEDERATED;
621 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
622 'network' => $networks, 'archive' => false, 'pending' => false];
623 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
624 while ($contact = DBA::fetch($contacts)) {
625 if (self::isValidReceiverForActor($contact, $actor, $tags)) {
626 $receivers['uid:' . $contact['uid']] = $contact['uid'];
629 DBA::close($contacts);
634 * Tests if the contact is a valid receiver for this actor
636 * @param array $contact
637 * @param string $actor
640 * @return bool with receivers (user id)
643 private static function isValidReceiverForActor($contact, $actor, $tags)
645 // Public contacts are no valid receiver
646 if ($contact['uid'] == 0) {
650 // Are we following the contact? Then this is a valid receiver
651 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
655 // When the possible receiver isn't a community, then it is no valid receiver
656 $owner = User::getOwnerDataById($contact['uid']);
657 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
661 // Is the community account tagged?
662 foreach ($tags as $tag) {
663 if ($tag['type'] != 'Mention') {
667 if ($tag['href'] == $owner['url']) {
676 * Switches existing contacts to ActivityPub
678 * @param integer $cid Contact ID
679 * @param integer $uid User ID
680 * @param string $url Profile URL
681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
682 * @throws \ImagickException
684 public static function switchContact($cid, $uid, $url)
686 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
687 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
691 if (Contact::updateFromProbe($cid, '', true)) {
692 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
695 // Send a new follow request to be sure that the connection still exists
696 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
697 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
698 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
707 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
708 * @throws \ImagickException
710 private static function switchContacts($receivers, $actor)
716 foreach ($receivers as $receiver) {
717 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
718 if (DBA::isResult($contact)) {
719 self::switchContact($contact['id'], $receiver, $actor);
722 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
723 if (DBA::isResult($contact)) {
724 self::switchContact($contact['id'], $receiver, $actor);
732 * @param $object_data
733 * @param array $activity
737 private static function addActivityFields($object_data, $activity)
739 if (!empty($activity['published']) && empty($object_data['published'])) {
740 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
743 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
744 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
747 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
748 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
750 if (!empty($object_data['object_id'])) {
751 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
752 $objectId = Item::getURIByLink($object_data['object_id']);
753 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
754 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
755 $object_data['object_id'] = $objectId;
763 * Fetches the object data from external ressources if needed
765 * @param string $object_id Object ID of the the provided object
766 * @param array $object The provided object array
767 * @param boolean $trust_source Do we trust the provided object?
768 * @param integer $uid User ID for the signature that we use to fetch data
770 * @return array|false with trusted and valid object data
771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
772 * @throws \ImagickException
774 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
776 // By fetching the type we check if the object is complete.
777 $type = JsonLD::fetchElement($object, '@type');
779 if (!$trust_source || empty($type)) {
780 $data = ActivityPub::fetchContent($object_id, $uid);
782 $object = JsonLD::compact($data);
783 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
785 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
787 $item = Item::selectFirst([], ['uri' => $object_id]);
788 if (!DBA::isResult($item)) {
789 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
792 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
793 $data = ActivityPub\Transmitter::createNote($item);
794 $object = JsonLD::compact($data);
797 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
800 $type = JsonLD::fetchElement($object, '@type');
803 Logger::log('Empty type', Logger::DEBUG);
807 if (in_array($type, self::CONTENT_TYPES)) {
808 return self::processObject($object);
811 if ($type == 'as:Announce') {
812 $object_id = JsonLD::fetchElement($object, 'object', '@id');
813 if (empty($object_id) || !is_string($object_id)) {
816 return self::fetchObject($object_id, [], false, $uid);
819 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
824 * Convert tags from JSON-LD format into a simplified format
826 * @param array $tags Tags in JSON-LD format
828 * @return array with tags in a simplified format
830 private static function processTags($tags)
838 foreach ($tags as $tag) {
843 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
844 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
845 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
847 if (empty($element['type'])) {
851 $taglist[] = $element;
857 * Convert emojis from JSON-LD format into a simplified format
860 * @return array with emojis in a simplified format
862 private static function processEmojis($emojis)
866 if (empty($emojis)) {
870 foreach ($emojis as $emoji) {
871 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
875 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
876 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
879 $emojilist[] = $element;
885 * Convert attachments from JSON-LD format into a simplified format
887 * @param array $attachments Attachments in JSON-LD format
889 * @return array with attachmants in a simplified format
891 private static function processAttachments($attachments)
895 if (empty($attachments)) {
899 foreach ($attachments as $attachment) {
900 if (empty($attachment)) {
904 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
905 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
906 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
907 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')];
913 * Fetch the original source or content with the "language" Markdown or HTML
915 * @param array $object
916 * @param array $object_data
921 private static function getSource($object, $object_data)
923 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
924 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
925 if (!empty($object_data['source'])) {
929 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
930 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
931 if (!empty($object_data['source'])) {
932 $object_data['source'] = Markdown::toBBCode($object_data['source']);
936 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
937 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
938 if (!empty($object_data['source'])) {
939 $object_data['source'] = HTML::toBBCode($object_data['source']);
947 * Fetches data from the object part of an activity
949 * @param array $object
954 private static function processObject($object)
956 if (!JsonLD::fetchElement($object, '@id')) {
961 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
962 $object_data['id'] = JsonLD::fetchElement($object, '@id');
963 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
965 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
966 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
967 $object_data['reply-to-id'] = $object_data['id'];
969 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
970 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
971 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
972 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
973 $object_data['reply-to-id'] = $replyToId;
977 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
978 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
980 if (empty($object_data['updated'])) {
981 $object_data['updated'] = $object_data['published'];
984 if (empty($object_data['published']) && !empty($object_data['updated'])) {
985 $object_data['published'] = $object_data['updated'];
988 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
990 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
993 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
994 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
995 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
996 $object_data['actor'] = $object_data['author'] = $actor;
997 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
998 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
999 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1000 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1001 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1002 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1003 $object_data = self::getSource($object, $object_data);
1004 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1005 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1006 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1007 $object_data['location'] = JsonLD::fetchElement($object_data, 'location', '@value');
1008 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1009 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1010 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1011 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1012 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
1013 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
1014 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
1015 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1016 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1017 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1019 // Special treatment for Hubzilla links
1020 if (is_array($object_data['alternate-url'])) {
1021 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1023 if (!is_string($object_data['alternate-url'])) {
1024 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1028 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']);
1030 // Common object data:
1033 // @context, type, actor, signature, mediaType, duration, replies, icon
1035 // Also missing: (Defined in the standard, but currently unused)
1036 // audience, preview, endTime, startTime, image
1041 // contentMap, announcement_count, announcements, context_id, likes, like_count
1042 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1047 // category, licence, language, commentsEnabled
1050 // views, waitTranscoding, state, support, subtitleLanguage
1051 // likes, dislikes, shares, comments
1053 return $object_data;