3 * @file src/Protocol/ActivityPub/Receiver.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Database\DBA;
8 use Friendica\Content\Text\HTML;
9 use Friendica\Content\Text\Markdown;
10 use Friendica\Core\Logger;
11 use Friendica\Core\Protocol;
12 use Friendica\Model\Contact;
13 use Friendica\Model\APContact;
14 use Friendica\Model\Conversation;
15 use Friendica\Model\Item;
16 use Friendica\Model\User;
17 use Friendica\Protocol\Activity;
18 use Friendica\Protocol\ActivityPub;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Util\HTTPSignature;
21 use Friendica\Util\JsonLD;
22 use Friendica\Util\LDSignature;
23 use Friendica\Util\Strings;
26 * @brief ActivityPub Receiver Protocol class
31 * Check what this is meant to do:
40 const PUBLIC_COLLECTION = 'as:Public';
41 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
42 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event'];
43 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
46 * Checks if the web request is done for the AP protocol
48 * @return bool is it AP?
50 public static function isRequest()
52 return stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/activity+json') ||
53 stristr($_SERVER['HTTP_ACCEPT'] ?? '', 'application/ld+json');
57 * Checks incoming message from the inbox
61 * @param integer $uid User ID
64 public static function processInbox($body, $header, $uid)
66 $http_signer = HTTPSignature::getSigner($body, $header);
67 if (empty($http_signer)) {
68 Logger::warning('Invalid HTTP signature, message will be discarded.');
71 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
74 $activity = json_decode($body, true);
76 if (empty($activity)) {
77 Logger::warning('Invalid body.');
81 $ldactivity = JsonLD::compact($activity);
83 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
85 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
87 if (LDSignature::isSigned($activity)) {
88 $ld_signer = LDSignature::getSigner($activity);
89 if (empty($ld_signer)) {
90 Logger::log('Invalid JSON-LD signature from ' . $actor, Logger::DEBUG);
92 if (!empty($ld_signer && ($actor == $http_signer))) {
93 Logger::log('The HTTP and the JSON-LD signature belong to ' . $ld_signer, Logger::DEBUG);
95 } elseif (!empty($ld_signer)) {
96 Logger::log('JSON-LD signature is signed by ' . $ld_signer, Logger::DEBUG);
98 } elseif ($actor == $http_signer) {
99 Logger::log('Bad JSON-LD signature, but HTTP signer fits the actor.', Logger::DEBUG);
100 $trust_source = true;
102 Logger::log('Invalid JSON-LD signature and the HTTP signer is different.', Logger::DEBUG);
103 $trust_source = false;
105 } elseif ($actor == $http_signer) {
106 Logger::log('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', Logger::DEBUG);
107 $trust_source = true;
109 Logger::log('No JSON-LD signature, different actor.', Logger::DEBUG);
110 $trust_source = false;
113 self::processActivity($ldactivity, $body, $uid, $trust_source);
117 * Fetches the object type for a given object id
119 * @param array $activity
120 * @param string $object_id Object ID of the the provided object
121 * @param integer $uid User ID
123 * @return string with object type
124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
125 * @throws \ImagickException
127 private static function fetchObjectType($activity, $object_id, $uid = 0)
129 if (!empty($activity['as:object'])) {
130 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
131 if (!empty($object_type)) {
136 if (Item::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
137 // We just assume "note" since it doesn't make a difference for the further processing
141 $profile = APContact::getByURL($object_id);
142 if (!empty($profile['type'])) {
143 return 'as:' . $profile['type'];
146 $data = ActivityPub::fetchContent($object_id, $uid);
148 $object = JsonLD::compact($data);
149 $type = JsonLD::fetchElement($object, '@type');
159 * Prepare the object array
161 * @param array $activity
162 * @param integer $uid User ID
163 * @param $trust_source
165 * @return array with object data
166 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
167 * @throws \ImagickException
169 private static function prepareObjectData($activity, $uid, &$trust_source)
171 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
173 Logger::log('Empty actor', Logger::DEBUG);
177 $type = JsonLD::fetchElement($activity, '@type');
179 // Fetch all receivers from to, cc, bto and bcc
180 $receivers = self::getReceivers($activity, $actor);
182 // When it is a delivery to a personal inbox we add that user to the receivers
184 $additional = ['uid:' . $uid => $uid];
185 $receivers = array_merge($receivers, $additional);
187 // We possibly need some user to fetch private content,
188 // so we fetch the first out ot the list.
189 $uid = self::getFirstUserFromReceivers($receivers);
192 Logger::log('Receivers: ' . $uid . ' - ' . json_encode($receivers), Logger::DEBUG);
194 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
195 if (empty($object_id)) {
196 Logger::log('No object found', Logger::DEBUG);
200 if (!is_string($object_id)) {
201 Logger::info('Invalid object id', ['object' => $object_id]);
205 $object_type = self::fetchObjectType($activity, $object_id, $uid);
207 // Fetch the content only on activities where this matters
208 if (in_array($type, ['as:Create', 'as:Update', 'as:Announce'])) {
209 if ($type == 'as:Announce') {
210 $trust_source = false;
212 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $uid);
213 if (empty($object_data)) {
214 Logger::log("Object data couldn't be processed", Logger::DEBUG);
217 $object_data['object_id'] = $object_id;
219 // Test if it is an answer to a mail
220 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
221 $object_data['directmessage'] = true;
223 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
226 // We had been able to retrieve the object data - so we can trust the source
227 $trust_source = true;
228 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
229 // Create a mostly empty array out of the activity data (instead of the object).
230 // This way we later don't have to check for the existence of ech individual array element.
231 $object_data = self::processObject($activity);
232 $object_data['name'] = $type;
233 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
234 $object_data['object_id'] = $object_id;
235 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
236 } elseif (in_array($type, ['as:Add'])) {
238 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
239 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
240 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
241 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
242 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
245 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
246 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
247 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
248 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
249 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
251 // An Undo is done on the object of an object, so we need that type as well
252 if ($type == 'as:Undo') {
253 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $uid);
257 $object_data = self::addActivityFields($object_data, $activity);
259 if (empty($object_data['object_type'])) {
260 $object_data['object_type'] = $object_type;
263 $object_data['type'] = $type;
264 $object_data['actor'] = $actor;
265 $object_data['item_receiver'] = $receivers;
266 $object_data['receiver'] = array_merge($object_data['receiver'] ?? [], $receivers);
268 Logger::log('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], Logger::DEBUG);
274 * Fetches the first user id from the receiver array
276 * @param array $receivers Array with receivers
277 * @return integer user id;
279 public static function getFirstUserFromReceivers($receivers)
281 foreach ($receivers as $receiver) {
282 if (!empty($receiver)) {
290 * Store the unprocessed data into the conversation table
291 * This has to be done outside the regular function,
292 * since we store everything - not only item posts.
294 * @param array $activity Array with activity data
295 * @param string $body The raw message
298 private static function storeConversation($activity, $body)
300 if (empty($body) || empty($activity['id'])) {
305 'protocol' => Conversation::PARCEL_ACTIVITYPUB,
306 'item-uri' => $activity['id'],
307 'reply-to-uri' => $activity['reply-to-id'] ?? '',
308 'conversation-href' => $activity['context'] ?? '',
309 'conversation-uri' => $activity['conversation'] ?? '',
311 'received' => DateTimeFormat::utcNow()];
313 DBA::insert('conversation', $conversation, true);
317 * Processes the activity object
319 * @param array $activity Array with activity data
320 * @param string $body
321 * @param integer $uid User ID
322 * @param boolean $trust_source Do we trust the source?
325 public static function processActivity($activity, $body = '', $uid = null, $trust_source = 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);
344 // Don't trust the source if "actor" differs from "attributedTo". The content could be forged.
345 if ($trust_source && ($type == 'as:Create') && is_array($activity['as:object'])) {
346 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
347 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
348 $trust_source = ($actor == $attributed_to);
349 if (!$trust_source) {
350 Logger::log('Not trusting actor: ' . $actor . '. It differs from attributedTo: ' . $attributed_to, Logger::DEBUG);
354 // $trust_source is called by reference and is set to true if the content was retrieved successfully
355 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
356 if (empty($object_data)) {
357 Logger::log('No object data found', Logger::DEBUG);
361 if (!$trust_source) {
362 Logger::log('No trust for activity type "' . $type . '", so we quit now.', Logger::DEBUG);
366 // Only store content related stuff - and no announces, since they possibly overwrite the original content
367 if (in_array($object_data['object_type'], self::CONTENT_TYPES) && ($type != 'as:Announce')) {
368 self::storeConversation($object_data, $body);
371 // Internal flag for thread completion. See Processor.php
372 if (!empty($activity['thread-completion'])) {
373 $object_data['thread-completion'] = $activity['thread-completion'];
378 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
379 ActivityPub\Processor::createItem($object_data);
384 if ($object_data['object_type'] == 'as:tag') {
385 ActivityPub\Processor::addTag($object_data);
390 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
391 $profile = APContact::getByURL($object_data['actor']);
392 // Reshared posts from persons appear as summary at the bottom
393 // If this isn't set, then a single reshare appears on top. This is used for groups.
394 $object_data['thread-completion'] = ($profile['type'] != 'Group');
396 ActivityPub\Processor::createItem($object_data);
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'];
406 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
412 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
413 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
418 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
419 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
423 case 'as:TentativeAccept':
424 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
425 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
430 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
431 ActivityPub\Processor::updateItem($object_data);
432 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
433 ActivityPub\Processor::updatePerson($object_data);
438 if ($object_data['object_type'] == 'as:Tombstone') {
439 ActivityPub\Processor::deleteItem($object_data);
440 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
441 ActivityPub\Processor::deletePerson($object_data);
446 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
447 ActivityPub\Processor::followUser($object_data);
448 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
449 $object_data['reply-to-id'] = $object_data['object_id'];
450 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
455 if ($object_data['object_type'] == 'as:Follow') {
456 ActivityPub\Processor::acceptFollowUser($object_data);
457 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
458 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
463 if ($object_data['object_type'] == 'as:Follow') {
464 ActivityPub\Processor::rejectFollowUser($object_data);
465 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
466 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
471 if (($object_data['object_type'] == 'as:Follow') &&
472 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
473 ActivityPub\Processor::undoFollowUser($object_data);
474 } elseif (($object_data['object_type'] == 'as:Accept') &&
475 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
476 ActivityPub\Processor::rejectFollowUser($object_data);
477 } elseif (in_array($object_data['object_type'], self::ACTIVITY_TYPES) &&
478 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
479 ActivityPub\Processor::undoActivity($object_data);
484 Logger::log('Unknown activity: ' . $type . ' ' . $object_data['object_type'], Logger::DEBUG);
490 * Fetch the receiver list from an activity array
492 * @param array $activity
493 * @param string $actor
496 * @return array with receivers (user id)
499 private static function getReceivers($activity, $actor, $tags = [])
503 // When it is an answer, we inherite the receivers from the parent
504 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
505 if (!empty($replyto)) {
506 $parents = Item::select(['uid'], ['uri' => $replyto]);
507 while ($parent = Item::fetch($parents)) {
508 $receivers['uid:' . $parent['uid']] = $parent['uid'];
512 if (!empty($actor)) {
513 $profile = APContact::getByURL($actor);
514 $followers = $profile['followers'] ?? '';
516 Logger::log('Actor: ' . $actor . ' - Followers: ' . $followers, Logger::DEBUG);
518 Logger::log('Empty actor', Logger::DEBUG);
522 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
523 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
524 if (empty($receiver_list)) {
528 foreach ($receiver_list as $receiver) {
529 if ($receiver == self::PUBLIC_COLLECTION) {
530 $receivers['uid:0'] = 0;
533 if (($receiver == self::PUBLIC_COLLECTION) && !empty($actor)) {
534 // This will most likely catch all OStatus connections to Mastodon
535 $condition = ['alias' => [$actor, Strings::normaliseLink($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]
536 , 'archive' => false, 'pending' => false];
537 $contacts = DBA::select('contact', ['uid'], $condition);
538 while ($contact = DBA::fetch($contacts)) {
539 if ($contact['uid'] != 0) {
540 $receivers['uid:' . $contact['uid']] = $contact['uid'];
543 DBA::close($contacts);
546 if (in_array($receiver, [$followers, self::PUBLIC_COLLECTION]) && !empty($actor)) {
547 $receivers = array_merge($receivers, self::getReceiverForActor($actor, $tags));
551 // Fetching all directly addressed receivers
552 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
553 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
554 if (!DBA::isResult($contact)) {
558 // Check if the potential receiver is following the actor
559 // Exception: The receiver is targetted via "to" or this is a comment
560 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
561 $networks = Protocol::FEDERATED;
562 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
563 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
565 // Forum posts are only accepted from forum contacts
566 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
567 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
570 if (!DBA::exists('contact', $condition)) {
575 $receivers['uid:' . $contact['uid']] = $contact['uid'];
579 self::switchContacts($receivers, $actor);
585 * Fetch the receiver list of a given actor
587 * @param string $actor
590 * @return array with receivers (user id)
593 public static function getReceiverForActor($actor, $tags)
596 $networks = Protocol::FEDERATED;
597 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
598 'network' => $networks, 'archive' => false, 'pending' => false];
599 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
600 while ($contact = DBA::fetch($contacts)) {
601 if (self::isValidReceiverForActor($contact, $actor, $tags)) {
602 $receivers['uid:' . $contact['uid']] = $contact['uid'];
605 DBA::close($contacts);
610 * Tests if the contact is a valid receiver for this actor
612 * @param array $contact
613 * @param string $actor
616 * @return bool with receivers (user id)
619 private static function isValidReceiverForActor($contact, $actor, $tags)
621 // Public contacts are no valid receiver
622 if ($contact['uid'] == 0) {
626 // Are we following the contact? Then this is a valid receiver
627 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
631 // When the possible receiver isn't a community, then it is no valid receiver
632 $owner = User::getOwnerDataById($contact['uid']);
633 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
637 // Is the community account tagged?
638 foreach ($tags as $tag) {
639 if ($tag['type'] != 'Mention') {
643 if ($tag['href'] == $owner['url']) {
652 * Switches existing contacts to ActivityPub
654 * @param integer $cid Contact ID
655 * @param integer $uid User ID
656 * @param string $url Profile URL
657 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
658 * @throws \ImagickException
660 public static function switchContact($cid, $uid, $url)
662 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
663 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
667 if (Contact::updateFromProbe($cid, '', true)) {
668 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
671 // Send a new follow request to be sure that the connection still exists
672 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
673 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
674 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
684 * @throws \ImagickException
686 private static function switchContacts($receivers, $actor)
692 foreach ($receivers as $receiver) {
693 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
694 if (DBA::isResult($contact)) {
695 self::switchContact($contact['id'], $receiver, $actor);
698 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
699 if (DBA::isResult($contact)) {
700 self::switchContact($contact['id'], $receiver, $actor);
708 * @param $object_data
709 * @param array $activity
713 private static function addActivityFields($object_data, $activity)
715 if (!empty($activity['published']) && empty($object_data['published'])) {
716 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
719 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
720 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
723 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
724 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
730 * Fetches the object data from external ressources if needed
732 * @param string $object_id Object ID of the the provided object
733 * @param array $object The provided object array
734 * @param boolean $trust_source Do we trust the provided object?
735 * @param integer $uid User ID for the signature that we use to fetch data
737 * @return array|false with trusted and valid object data
738 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
739 * @throws \ImagickException
741 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
743 // By fetching the type we check if the object is complete.
744 $type = JsonLD::fetchElement($object, '@type');
746 if (!$trust_source || empty($type)) {
747 $data = ActivityPub::fetchContent($object_id, $uid);
749 $object = JsonLD::compact($data);
750 Logger::log('Fetched content for ' . $object_id, Logger::DEBUG);
752 Logger::log('Empty content for ' . $object_id . ', check if content is available locally.', Logger::DEBUG);
754 $item = Item::selectFirst([], ['uri' => $object_id]);
755 if (!DBA::isResult($item)) {
756 Logger::log('Object with url ' . $object_id . ' was not found locally.', Logger::DEBUG);
759 Logger::log('Using already stored item for url ' . $object_id, Logger::DEBUG);
760 $data = ActivityPub\Transmitter::createNote($item);
761 $object = JsonLD::compact($data);
764 Logger::log('Using original object for url ' . $object_id, Logger::DEBUG);
767 $type = JsonLD::fetchElement($object, '@type');
770 Logger::log('Empty type', Logger::DEBUG);
774 if (in_array($type, self::CONTENT_TYPES)) {
775 return self::processObject($object);
778 if ($type == 'as:Announce') {
779 $object_id = JsonLD::fetchElement($object, 'object', '@id');
780 if (empty($object_id) || !is_string($object_id)) {
783 return self::fetchObject($object_id, [], false, $uid);
786 Logger::log('Unhandled object type: ' . $type, Logger::DEBUG);
791 * Convert tags from JSON-LD format into a simplified format
793 * @param array $tags Tags in JSON-LD format
795 * @return array with tags in a simplified format
797 private static function processTags($tags)
805 foreach ($tags as $tag) {
810 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
811 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
812 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
814 if (empty($element['type'])) {
818 $taglist[] = $element;
824 * Convert emojis from JSON-LD format into a simplified format
827 * @return array with emojis in a simplified format
829 private static function processEmojis($emojis)
833 if (empty($emojis)) {
837 foreach ($emojis as $emoji) {
838 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
842 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
843 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
846 $emojilist[] = $element;
852 * Convert attachments from JSON-LD format into a simplified format
854 * @param array $attachments Attachments in JSON-LD format
856 * @return array with attachmants in a simplified format
858 private static function processAttachments($attachments)
862 if (empty($attachments)) {
866 foreach ($attachments as $attachment) {
867 if (empty($attachment)) {
871 $attachlist[] = ['type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
872 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
873 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
874 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id')];
880 * Fetch the original source or content with the "language" Markdown or HTML
882 * @param array $object
883 * @param array $object_data
888 private static function getSource($object, $object_data)
890 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
891 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
892 if (!empty($object_data['source'])) {
896 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
897 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
898 if (!empty($object_data['source'])) {
899 $object_data['source'] = Markdown::toBBCode($object_data['source']);
903 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
904 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
905 if (!empty($object_data['source'])) {
906 $object_data['source'] = HTML::toBBCode($object_data['source']);
910 $markdown = JsonLD::fetchElement($object, 'as:content', '@value', '@language', 'text/markdown');
911 if (!empty($markdown)) {
912 $object_data['source'] = Markdown::toBBCode($markdown);
916 $html = JsonLD::fetchElement($object, 'as:content', '@value', '@language', 'text/html');
918 $object_data['source'] = HTML::toBBCode($markdown);
926 * Fetches data from the object part of an activity
928 * @param array $object
933 private static function processObject($object)
935 if (!JsonLD::fetchElement($object, '@id')) {
940 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
941 $object_data['id'] = JsonLD::fetchElement($object, '@id');
942 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
944 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
945 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
946 $object_data['reply-to-id'] = $object_data['id'];
949 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
950 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
952 if (empty($object_data['updated'])) {
953 $object_data['updated'] = $object_data['published'];
956 if (empty($object_data['published']) && !empty($object_data['updated'])) {
957 $object_data['published'] = $object_data['updated'];
960 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
962 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
965 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
966 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
967 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
968 $object_data['actor'] = $object_data['author'] = $actor;
969 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
970 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
971 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
972 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
973 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
974 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
975 $object_data = self::getSource($object, $object_data);
976 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
977 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
978 $object_data['location'] = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
979 $object_data['location'] = JsonLD::fetchElement($object_data, 'location', '@value');
980 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
981 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
982 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
983 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
984 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment'));
985 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag'));
986 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', 'toot:Emoji'));
987 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
988 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
989 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
991 // Special treatment for Hubzilla links
992 if (is_array($object_data['alternate-url'])) {
993 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
995 if (!is_string($object_data['alternate-url'])) {
996 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1000 $object_data['receiver'] = self::getReceivers($object, $object_data['actor'], $object_data['tags']);
1002 // Common object data:
1005 // @context, type, actor, signature, mediaType, duration, replies, icon
1007 // Also missing: (Defined in the standard, but currently unused)
1008 // audience, preview, endTime, startTime, image
1013 // contentMap, announcement_count, announcements, context_id, likes, like_count
1014 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1019 // category, licence, language, commentsEnabled
1022 // views, waitTranscoding, state, support, subtitleLanguage
1023 // likes, dislikes, shares, comments
1025 return $object_data;