3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
32 use Friendica\Model\Contact;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Util\HTTPSignature;
40 use Friendica\Util\JsonLD;
41 use Friendica\Util\LDSignature;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
46 * ActivityPub Receiver Protocol class
51 * Check what this is meant to do:
60 const PUBLIC_COLLECTION = 'as:Public';
61 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
62 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
63 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
65 const TARGET_UNKNOWN = 0;
70 const TARGET_FOLLOWER = 5;
71 const TARGET_ANSWER = 6;
72 const TARGET_GLOBAL = 7;
74 const COMPLETION_NONE = 0;
75 const COMPLETION_ANNOUCE = 1;
76 const COMPLETION_RELAY = 2;
77 const COMPLETION_MANUAL = 3;
78 const COMPLETION_AUTO = 4;
81 * Checks incoming message from the inbox
83 * @param string $body Body string
84 * @param array $header Header lines
85 * @param integer $uid User ID
89 public static function processInbox(string $body, array $header, int $uid)
91 $activity = json_decode($body, true);
92 if (empty($activity)) {
93 Logger::warning('Invalid body.');
97 $ldactivity = JsonLD::compact($activity);
99 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
101 $apcontact = APContact::getByURL($actor);
103 if (empty($apcontact)) {
104 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
106 } elseif (APContact::isRelay($apcontact)) {
107 self::processRelayPost($ldactivity, $actor);
110 APContact::unmarkForArchival($apcontact);
113 $http_signer = HTTPSignature::getSigner($body, $header);
114 if ($http_signer === false) {
115 Logger::warning('Invalid HTTP signature, message will be discarded.');
117 } elseif (empty($http_signer)) {
118 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
121 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
124 $signer = [$http_signer];
126 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
128 if (LDSignature::isSigned($activity)) {
129 $ld_signer = LDSignature::getSigner($activity);
130 if (empty($ld_signer)) {
131 Logger::info('Invalid JSON-LD signature from ' . $actor);
132 } elseif ($ld_signer != $http_signer) {
133 $signer[] = $ld_signer;
135 if (!empty($ld_signer && ($actor == $http_signer))) {
136 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
137 $trust_source = true;
138 } elseif (!empty($ld_signer)) {
139 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
140 $trust_source = true;
141 } elseif ($actor == $http_signer) {
142 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
143 $trust_source = true;
145 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
146 $trust_source = false;
148 } elseif ($actor == $http_signer) {
149 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
150 $trust_source = true;
152 Logger::info('No JSON-LD signature, different actor.');
153 $trust_source = false;
156 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
160 * Process incoming posts from relays
162 * @param array $activity
163 * @param string $actor
166 private static function processRelayPost(array $activity, string $actor)
168 $type = JsonLD::fetchElement($activity, '@type');
170 Logger::info('Empty type', ['activity' => $activity, 'actor' => $actor]);
174 if ($type != 'as:Announce') {
175 Logger::info('Not an announcement', ['activity' => $activity, 'actor' => $actor]);
179 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
180 if (empty($object_id)) {
181 Logger::info('No object id found', ['activity' => $activity, 'actor' => $actor]);
185 $contact = Contact::getByURL($actor);
186 if (empty($contact)) {
187 Logger::info('Relay contact not found', ['actor' => $actor]);
191 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
192 Logger::notice('Relay is no sharer', ['actor' => $actor]);
196 Logger::info('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
198 $item_id = Item::searchByLink($object_id);
200 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
204 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
206 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
210 $item_id = Item::searchByLink($object_id);
212 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
214 Logger::notice('Relayed message had not been stored', ['id' => $object_id, 'actor' => $actor]);
219 * Fetches the object type for a given object id
221 * @param array $activity
222 * @param string $object_id Object ID of the the provided object
223 * @param integer $uid User ID
225 * @return string with object type or NULL
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @throws \ImagickException
229 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
231 if (!empty($activity['as:object'])) {
232 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
233 if (!empty($object_type)) {
238 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
239 // We just assume "note" since it doesn't make a difference for the further processing
243 $profile = APContact::getByURL($object_id);
244 if (!empty($profile['type'])) {
245 APContact::unmarkForArchival($profile);
246 return 'as:' . $profile['type'];
249 $data = ActivityPub::fetchContent($object_id, $uid);
251 $object = JsonLD::compact($data);
252 $type = JsonLD::fetchElement($object, '@type');
262 * Prepare the object array
264 * @param array $activity Array with activity data
265 * @param integer $uid User ID
266 * @param boolean $push Message had been pushed to our system
267 * @param boolean $trust_source Do we trust the source?
269 * @return array with object data
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 * @throws \ImagickException
273 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
275 $id = JsonLD::fetchElement($activity, '@id');
276 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
278 if (!empty($id) && !$trust_source) {
279 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
281 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
282 if (!empty($fetched_activity)) {
283 $object = JsonLD::compact($fetched_activity);
284 $fetched_id = JsonLD::fetchElement($object, '@id');
285 if ($fetched_id == $id) {
286 Logger::info('Activity had been fetched successfully', ['id' => $id]);
287 $trust_source = true;
288 if ($id != $object_id) {
291 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
292 unset($object['@context']);
293 $activity['as:object'] = $object;
296 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
299 Logger::info('Activity could not been fetched', ['id' => $id]);
303 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
305 Logger::info('Empty actor', ['activity' => $activity]);
309 $type = JsonLD::fetchElement($activity, '@type');
311 // Fetch all receivers from to, cc, bto and bcc
312 $receiverdata = self::getReceivers($activity, $actor);
313 $receivers = $reception_types = [];
314 foreach ($receiverdata as $key => $data) {
315 $receivers[$key] = $data['uid'];
316 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
319 $urls = self::getReceiverURL($activity);
321 // When it is a delivery to a personal inbox we add that user to the receivers
323 $additional = [$uid => $uid];
324 $receivers = array_replace($receivers, $additional);
325 if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
326 $reception_types[$uid] = self::TARGET_BCC;
327 $owner = User::getOwnerDataById($uid);
328 if (!empty($owner['url'])) {
329 $urls['as:bcc'][] = $owner['url'];
334 // We possibly need some user to fetch private content,
335 // so we fetch one out of the receivers if no uid is provided.
336 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
338 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
339 if (empty($object_id)) {
340 Logger::info('No object found');
344 if (!is_string($object_id)) {
345 Logger::info('Invalid object id', ['object' => $object_id]);
349 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
351 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
352 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
353 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
355 $type = $object_type;
356 $activity = JsonLD::compact($data);
358 // Some variables need to be refetched since the activity changed
359 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
360 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
361 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
365 // Any activities on account types must not be altered
366 if (in_array($object_type, self::ACCOUNT_TYPES)) {
368 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
369 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
370 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
371 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
372 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
373 $object_data['push'] = $push;
374 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
375 // Fetch the content only on activities where this matters
376 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
377 // Always fetch on "Announce"
378 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
379 if (empty($object_data)) {
380 Logger::info("Object data couldn't be processed");
384 $object_data['object_id'] = $object_id;
386 if ($type == 'as:Announce') {
387 $object_data['push'] = false;
389 $object_data['push'] = $push;
392 // Test if it is an answer to a mail
393 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
394 $object_data['directmessage'] = true;
396 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
398 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
399 // Create a mostly empty array out of the activity data (instead of the object).
400 // This way we later don't have to check for the existence of each individual array element.
401 $object_data = self::processObject($activity);
402 $object_data['name'] = $type;
403 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
404 $object_data['object_id'] = $object_id;
405 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
406 $object_data['push'] = $push;
407 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
409 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
410 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
411 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
412 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
413 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
414 $object_data['push'] = $push;
417 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
418 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
419 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
420 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
421 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
422 $object_data['push'] = $push;
424 // An Undo is done on the object of an object, so we need that type as well
425 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
426 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
430 $object_data = self::addActivityFields($object_data, $activity);
432 if (empty($object_data['object_type'])) {
433 $object_data['object_type'] = $object_type;
436 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
437 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
438 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
442 $object_data['type'] = $type;
443 $object_data['actor'] = $actor;
444 $object_data['item_receiver'] = $receivers;
445 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
446 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
448 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
449 // $author = $object_data['author'] ?? $actor;
450 // if (!empty($author) && !empty($object_data['id'])) {
451 // $author_host = parse_url($author, PHP_URL_HOST);
452 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
453 // if ($author_host == $id_host) {
454 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
456 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
457 // $trust_source = false;
461 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
467 * Fetches the first user id from the receiver array
469 * @param array $receivers Array with receivers
470 * @return integer user id;
472 public static function getFirstUserFromReceivers(array $receivers): int
474 foreach ($receivers as $receiver) {
475 if (!empty($receiver)) {
483 * Processes the activity object
485 * @param array $activity Array with activity data
486 * @param string $body The unprocessed body
487 * @param int|null $uid User ID
488 * @param boolean $trust_source Do we trust the source?
489 * @param boolean $push Message had been pushed to our system
490 * @param array $signer The signer of the post
491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
492 * @throws \ImagickException
494 public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '')
496 $type = JsonLD::fetchElement($activity, '@type');
498 Logger::info('Empty type', ['activity' => $activity]);
502 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
503 Logger::info('Empty object', ['activity' => $activity]);
507 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
509 Logger::info('Empty actor', ['activity' => $activity]);
513 if (is_array($activity['as:object'])) {
514 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
519 // Test the provided signatures against the actor and "attributedTo"
521 if (!empty($attributed_to) && !empty($actor)) {
522 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
524 $trust_source = in_array($actor, $signer);
528 // $trust_source is called by reference and is set to true if the content was retrieved successfully
529 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
530 if (empty($object_data)) {
531 Logger::info('No object data found', ['activity' => $activity]);
535 // Lemmy is announcing activities.
536 // We are changing the announces into regular activities.
537 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
538 $type = $object_data['type'];
541 if (!empty($body) && empty($object_data['raw'])) {
542 $object_data['raw'] = $body;
545 // Internal flag for thread completion. See Processor.php
546 if (!empty($activity['thread-completion'])) {
547 $object_data['thread-completion'] = $activity['thread-completion'];
550 if (!empty($activity['completion-mode'])) {
551 $object_data['completion-mode'] = $activity['completion-mode'];
554 if (!empty($activity['thread-children-type'])) {
555 $object_data['thread-children-type'] = $activity['thread-children-type'];
558 // Internal flag for posts that arrived via relay
559 if (!empty($activity['from-relay'])) {
560 $object_data['from-relay'] = $activity['from-relay'];
563 if ($type == 'as:Announce') {
564 $object_data['object_activity'] = $activity;
567 if ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted')) {
568 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
571 if (!$trust_source) {
572 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
576 if (!empty($activity['recursion-depth'])) {
577 $object_data['recursion-depth'] = $activity['recursion-depth'];
580 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
581 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
584 if (!self::routeActivities($object_data, $type, $push)) {
585 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
586 Queue::remove($object_data);
593 * @param array $object_data
594 * @param string $type
595 * @param boolean $push
597 * @return boolean Could the activity be routed?
599 public static function routeActivities(array $object_data, string $type, bool $push): bool
601 $activity = $object_data['object_activity'] ?? [];
605 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
606 $item = ActivityPub\Processor::createItem($object_data);
607 ActivityPub\Processor::postItem($object_data, $item);
608 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
609 // Unhandled Peertube activity
610 Queue::remove($object_data);
617 if (in_array($object_data['object_type'], ['as:Event'])) {
618 $item = ActivityPub\Processor::createItem($object_data);
619 ActivityPub\Processor::postItem($object_data, $item);
626 if ($object_data['object_type'] == 'as:tag') {
627 ActivityPub\Processor::addTag($object_data);
628 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
629 ActivityPub\Processor::addToFeaturedCollection($object_data);
630 } elseif ($object_data['object_type'] == '') {
631 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
632 Queue::remove($object_data);
639 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
640 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
641 $object_data['thread-completion'] = Contact::getIdForURL($actor);
642 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
644 $item = ActivityPub\Processor::createItem($object_data);
649 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
650 ActivityPub\Processor::postItem($object_data, $item);
652 if (!empty($activity)) {
653 $announce_object_data = self::processObject($activity);
654 $announce_object_data['name'] = $type;
655 $announce_object_data['author'] = $actor;
656 $announce_object_data['object_id'] = $object_data['object_id'];
657 $announce_object_data['object_type'] = $object_data['object_type'];
658 $announce_object_data['push'] = $push;
660 if (!empty($object_data['raw'])) {
661 $announce_object_data['raw'] = $object_data['raw'];
663 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
671 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
672 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
673 } elseif ($object_data['object_type'] == '') {
674 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
675 Queue::remove($object_data);
682 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
683 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
684 } elseif ($object_data['object_type'] == '') {
685 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
686 Queue::remove($object_data);
692 case 'as:TentativeAccept':
693 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
694 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
701 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
702 ActivityPub\Processor::updateItem($object_data);
703 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
704 ActivityPub\Processor::updatePerson($object_data);
705 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
706 // Unhandled Peertube activity
707 Queue::remove($object_data);
714 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
715 ActivityPub\Processor::deleteItem($object_data);
716 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
717 ActivityPub\Processor::deletePerson($object_data);
718 } elseif ($object_data['object_type'] == '') {
719 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
720 Queue::remove($object_data);
727 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
728 ActivityPub\Processor::blockAccount($object_data);
735 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
736 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
737 } elseif ($object_data['object_type'] == '') {
738 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
739 Queue::remove($object_data);
746 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
747 ActivityPub\Processor::followUser($object_data);
748 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
749 $object_data['reply-to-id'] = $object_data['object_id'];
750 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
757 if ($object_data['object_type'] == 'as:Follow') {
758 ActivityPub\Processor::acceptFollowUser($object_data);
759 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
760 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
767 if ($object_data['object_type'] == 'as:Follow') {
768 ActivityPub\Processor::rejectFollowUser($object_data);
769 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
770 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
777 if (($object_data['object_type'] == 'as:Follow') &&
778 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
779 ActivityPub\Processor::undoFollowUser($object_data);
780 } elseif (($object_data['object_type'] == 'as:Follow') &&
781 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
782 ActivityPub\Processor::undoActivity($object_data);
783 } elseif (($object_data['object_type'] == 'as:Accept') &&
784 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
785 ActivityPub\Processor::rejectFollowUser($object_data);
786 } elseif (($object_data['object_type'] == 'as:Block') &&
787 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
788 ActivityPub\Processor::unblockAccount($object_data);
789 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
790 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
791 ActivityPub\Processor::undoActivity($object_data);
792 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
793 empty($object_data['object_object_type'])) {
794 // We cannot detect the target object. So we can ignore it.
795 Queue::remove($object_data);
796 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
797 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
798 // Unhandled Peertube activity
799 Queue::remove($object_data);
806 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
807 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
808 } elseif ($object_data['object_type'] == '') {
809 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
810 Queue::remove($object_data);
816 case 'litepub:EmojiReact':
817 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
818 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
819 } elseif ($object_data['object_type'] == '') {
820 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
821 Queue::remove($object_data);
828 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
835 * Stores unhandled or unknown Activities as a file
837 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
838 * @param string $type Activity type
839 * @param array $object_data Preprocessed array that is generated out of the received activity
840 * @param array $activity Array with activity data
841 * @param string $body The unprocessed body
842 * @param integer $uid User ID
843 * @param boolean $trust_source Do we trust the source?
844 * @param boolean $push Message had been pushed to our system
845 * @param array $signer The signer of the post
848 private static function storeUnhandledActivity(bool $unknown, string $type, array $object_data, array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
850 if (!DI::config()->get('debug', 'ap_log_unknown')) {
854 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
856 if (!empty($object_data['object_type'])) {
857 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
860 if (!empty($object_data['object_object_type'])) {
861 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
864 $tempfile = tempnam(System::getTempPath(), $file);
865 file_put_contents($tempfile, json_encode(['activity' => $activity, 'body' => $body, 'uid' => $uid, 'trust_source' => $trust_source, 'push' => $push, 'signer' => $signer, 'object_data' => $object_data], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
866 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
870 * Fetch a user id from an activity array
872 * @param array $activity
873 * @param string $actor
875 * @return int user id
877 public static function getBestUserForActivity(array $activity): int
880 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
882 $receivers = self::getReceivers($activity, $actor);
883 foreach ($receivers as $receiver) {
884 if ($receiver['type'] == self::TARGET_GLOBAL) {
887 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
888 $uid = $receiver['uid'];
892 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
894 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
895 if (!empty($contact['uid'])) {
896 $uid = $contact['uid'];
903 // @TODO Missing documentation
904 public static function getReceiverURL(array $activity): array
908 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
909 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
910 if (empty($receiver_list)) {
914 foreach ($receiver_list as $receiver) {
915 if ($receiver == self::PUBLIC_COLLECTION) {
916 $receiver = ActivityPub::PUBLIC_COLLECTION;
918 $urls[$element][] = $receiver;
926 * Fetch the receiver list from an activity array
928 * @param array $activity
929 * @param string $actor
931 * @param boolean $fetch_unlisted
933 * @return array with receivers (user id)
936 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
938 $reply = $receivers = $profile = [];
940 // When it is an answer, we inherite the receivers from the parent
941 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
942 if (!empty($replyto)) {
945 // Fix possibly wrong item URI (could be an answer to a plink uri)
946 $fixedReplyTo = Item::getURIByLink($replyto);
947 if (!empty($fixedReplyTo)) {
948 $reply[] = $fixedReplyTo;
952 // Fetch all posts that refer to the object id
953 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
954 if (!empty($object_id)) {
955 $reply[] = $object_id;
958 if (!empty($reply)) {
959 $parents = Post::select(['uid'], ['uri' => $reply]);
960 while ($parent = Post::fetch($parents)) {
961 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
963 DBA::close($parents);
966 if (!empty($actor)) {
967 $profile = APContact::getByURL($actor);
968 $followers = $profile['followers'] ?? '';
969 $is_forum = ($actor['type'] ?? '') == 'Group';
970 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
972 Logger::info('Empty actor', ['activity' => $activity]);
977 // We have to prevent false follower assumptions upon thread completions
978 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
980 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
981 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
982 if (empty($receiver_list)) {
986 foreach ($receiver_list as $receiver) {
987 if ($receiver == self::PUBLIC_COLLECTION) {
988 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
991 // Add receiver "-1" for unlisted posts
992 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
993 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
996 // Fetch the receivers for the public and the followers collection
997 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
998 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1002 // Fetching all directly addressed receivers
1003 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1004 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1005 if (!DBA::isResult($contact)) {
1009 // Check if the potential receiver is following the actor
1010 // Exception: The receiver is targetted via "to" or this is a comment
1011 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1012 $networks = Protocol::FEDERATED;
1013 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1014 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1016 // Forum posts are only accepted from forum contacts
1017 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1018 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1021 if (!DBA::exists('contact', $condition)) {
1026 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1027 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1030 $type = self::TARGET_TO;
1033 $type = self::TARGET_CC;
1036 $type = self::TARGET_BTO;
1039 $type = self::TARGET_BCC;
1043 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1048 self::switchContacts($receivers, $actor);
1054 * Fetch the receiver list of a given actor
1056 * @param string $actor
1057 * @param array $tags
1058 * @param array $receivers
1059 * @param integer $target_type
1060 * @param array $profile
1062 * @return array with receivers (user id)
1063 * @throws \Exception
1065 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1067 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1068 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1070 if (!empty($profile['uri-id'])) {
1071 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1072 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1073 while ($contact = DBA::fetch($contacts)) {
1074 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1075 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1078 DBA::close($contacts);
1080 // This part will only be called while post update 1426 wasn't finished
1081 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1082 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1083 while ($contact = DBA::fetch($contacts)) {
1084 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1085 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1088 DBA::close($contacts);
1090 // The queries are split because of performance issues
1091 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1092 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1093 while ($contact = DBA::fetch($contacts)) {
1094 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1095 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1098 DBA::close($contacts);
1104 * Tests if the contact is a valid receiver for this actor
1106 * @param array $contact
1107 * @param array $tags
1109 * @return bool with receivers (user id)
1110 * @throws \Exception
1112 private static function isValidReceiverForActor(array $contact, array $tags): bool
1114 // Are we following the contact? Then this is a valid receiver
1115 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1119 // When the possible receiver isn't a community, then it is no valid receiver
1120 $owner = User::getOwnerDataById($contact['uid']);
1121 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1125 // Is the community account tagged?
1126 foreach ($tags as $tag) {
1127 if ($tag['type'] != 'Mention') {
1131 if (Strings::compareLink($tag['href'], $owner['url'])) {
1140 * Switches existing contacts to ActivityPub
1142 * @param integer $cid Contact ID
1143 * @param integer $uid User ID
1144 * @param string $url Profile URL
1146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1147 * @throws \ImagickException
1149 public static function switchContact(int $cid, int $uid, string $url)
1151 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1152 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1156 if (Contact::updateFromProbe($cid)) {
1157 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1160 // Send a new follow request to be sure that the connection still exists
1161 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1162 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1163 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1168 * @TODO Fix documentation and type-hints
1173 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1174 * @throws \ImagickException
1176 private static function switchContacts($receivers, $actor)
1178 if (empty($actor)) {
1182 foreach ($receivers as $receiver) {
1183 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1184 if (DBA::isResult($contact)) {
1185 self::switchContact($contact['id'], $receiver['uid'], $actor);
1188 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1189 if (DBA::isResult($contact)) {
1190 self::switchContact($contact['id'], $receiver['uid'], $actor);
1196 * @TODO Fix documentation and type-hints
1198 * @param $object_data
1199 * @param array $activity
1203 private static function addActivityFields($object_data, array $activity)
1205 if (!empty($activity['published']) && empty($object_data['published'])) {
1206 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1209 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1210 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1213 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1214 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1216 if (!empty($object_data['object_id'])) {
1217 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1218 $objectId = Item::getURIByLink($object_data['object_id']);
1219 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1220 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1221 $object_data['object_id'] = $objectId;
1225 return $object_data;
1229 * Fetches the object data from external ressources if needed
1231 * @param string $object_id Object ID of the the provided object
1232 * @param array $object The provided object array
1233 * @param boolean $trust_source Do we trust the provided object?
1234 * @param integer $uid User ID for the signature that we use to fetch data
1236 * @return array|false with trusted and valid object data
1237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1238 * @throws \ImagickException
1240 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1242 // By fetching the type we check if the object is complete.
1243 $type = JsonLD::fetchElement($object, '@type');
1245 if (!$trust_source || empty($type)) {
1246 $data = ActivityPub::fetchContent($object_id, $uid);
1247 if (!empty($data)) {
1248 $object = JsonLD::compact($data);
1249 Logger::info('Fetched content for ' . $object_id);
1251 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1253 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1254 if (!DBA::isResult($item)) {
1255 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1258 Logger::info('Using already stored item for url ' . $object_id);
1259 $data = ActivityPub\Transmitter::createNote($item);
1260 $object = JsonLD::compact($data);
1263 $id = JsonLD::fetchElement($object, '@id');
1265 Logger::info('Empty id');
1269 if ($id != $object_id) {
1270 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1274 Logger::info('Using original object for url ' . $object_id);
1277 $type = JsonLD::fetchElement($object, '@type');
1279 Logger::info('Empty type');
1283 // Lemmy is resharing "create" activities instead of content
1284 // We fetch the content from the activity.
1285 if (in_array($type, ['as:Create'])) {
1286 $object = $object['as:object'];
1287 $type = JsonLD::fetchElement($object, '@type');
1289 Logger::info('Empty type');
1292 $object_data = self::processObject($object);
1295 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1296 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1297 $object_data = self::processObject($object);
1299 if (!empty($data)) {
1300 $object_data['raw'] = json_encode($data);
1302 return $object_data;
1305 if ($type == 'as:Announce') {
1306 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1307 if (empty($object_id) || !is_string($object_id)) {
1310 return self::fetchObject($object_id, [], false, $uid);
1313 Logger::info('Unhandled object type: ' . $type);
1318 * Converts the language element (Used by Peertube)
1320 * @param array $languages
1321 * @return array Languages
1323 public static function processLanguages(array $languages): array
1325 if (empty($languages)) {
1329 $language_list = [];
1331 foreach ($languages as $language) {
1332 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1333 $language_list[$language['_:identifier']] = $language['as:name'];
1336 return $language_list;
1340 * Convert tags from JSON-LD format into a simplified format
1342 * @param array $tags Tags in JSON-LD format
1344 * @return array with tags in a simplified format
1346 public static function processTags(array $tags): array
1350 foreach ($tags as $tag) {
1355 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1356 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1357 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1359 if (empty($element['type'])) {
1363 if (empty($element['href'])) {
1364 $element['href'] = $element['name'];
1367 $taglist[] = $element;
1373 * Convert emojis from JSON-LD format into a simplified format
1375 * @param array $emojis
1376 * @return array with emojis in a simplified format
1378 private static function processEmojis(array $emojis): array
1382 foreach ($emojis as $emoji) {
1383 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1387 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1388 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1391 $emojilist[] = $element;
1398 * Convert attachments from JSON-LD format into a simplified format
1400 * @param array $attachments Attachments in JSON-LD format
1402 * @return array Attachments in a simplified format
1404 private static function processAttachments(array $attachments): array
1408 // Removes empty values
1409 $attachments = array_filter($attachments);
1411 foreach ($attachments as $attachment) {
1412 switch (JsonLD::fetchElement($attachment, '@type')) {
1417 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1418 foreach ($urls as $url) {
1419 // Single scalar URL case
1420 if (is_string($url)) {
1425 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1426 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1427 if (Strings::startsWith($mediaType, 'image')) {
1436 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1437 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1439 'image' => $pageImage,
1443 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1444 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1445 $imagePreviewUrl = null;
1447 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1448 $imageVariants = [];
1449 $previewVariants = [];
1450 foreach ($urls as $url) {
1451 // Scalar URL, no discrimination possible
1452 if (is_string($url)) {
1453 $imageFullUrl = $url;
1457 // Not sure what to do with a different Link media type than the base Image, we skip
1458 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1462 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1464 // Default URL choice if no discriminating width is provided
1465 $imageFullUrl = $href ?? $imageFullUrl;
1467 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1469 if ($href && $width) {
1470 $imageVariants[$width] = $href;
1471 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1472 $previewVariants[abs(632 - $width)] = $href;
1476 if ($imageVariants) {
1477 // Taking the maximum size image
1478 ksort($imageVariants);
1479 $imageFullUrl = array_pop($imageVariants);
1481 // Taking the minimum number distance to the target distance
1482 ksort($previewVariants);
1483 $imagePreviewUrl = array_shift($previewVariants);
1486 unset($imageVariants);
1487 unset($previewVariants);
1491 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1492 'mediaType' => $mediaType,
1493 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1494 'url' => $imageFullUrl,
1495 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1500 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1501 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1502 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1503 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1504 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1505 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1506 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1515 * Convert questions from JSON-LD format into a simplified format
1517 * @param array $object
1519 * @return array Questions in a simplified format
1521 private static function processQuestion(array $object): array
1525 if (!empty($object['as:oneOf'])) {
1526 $question['multiple'] = false;
1527 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1528 } elseif (!empty($object['as:anyOf'])) {
1529 $question['multiple'] = true;
1530 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1535 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1536 if (!empty($closed)) {
1537 $question['end-time'] = $closed;
1539 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1542 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1543 $question['options'] = [];
1547 foreach ($options as $option) {
1548 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1552 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1554 if (empty($option['as:replies'])) {
1558 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1560 $question['options'][] = ['name' => $name, 'replies' => $replies];
1562 $voters += (int)$replies;
1565 // For single choice question we can count the number of voters if not provided (like with Misskey)
1566 if (empty($question['voters']) && !$question['multiple']) {
1567 $question['voters'] = $voters;
1574 * Fetch the original source or content with the "language" Markdown or HTML
1576 * @param array $object
1577 * @param array $object_data
1579 * @return array Object data (?)
1580 * @throws \Exception
1582 private static function getSource(array $object, array $object_data): array
1584 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1585 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1586 if (!empty($object_data['source'])) {
1587 return $object_data;
1590 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1591 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1592 if (!empty($object_data['source'])) {
1593 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1594 return $object_data;
1597 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1598 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1599 if (!empty($object_data['source'])) {
1600 $object_data['source'] = HTML::toBBCode($object_data['source']);
1601 return $object_data;
1604 return $object_data;
1608 * Extracts a potential alternate URL from a list of additional URL elements
1610 * @param array $urls
1613 private static function extractAlternateUrl(array $urls): string
1616 foreach ($urls as $key => $url) {
1617 // Not a list but a single URL element
1618 if (!is_numeric($key)) {
1622 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1626 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1631 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1632 if (empty($mediatype)) {
1636 if ($mediatype == 'text/html') {
1637 $alternateUrl = $href;
1641 return $alternateUrl;
1645 * Check if the "as:url" element is an array with multiple links
1646 * This is the case with audio and video posts.
1647 * Then the links are added as attachments
1649 * @param array $urls The object URL list
1650 * @return array an array of attachments
1652 private static function processAttachmentUrls(array $urls): array
1655 foreach ($urls as $key => $url) {
1656 // Not a list but a single URL element
1657 if (!is_numeric($key)) {
1661 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1665 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1670 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1671 if (empty($mediatype)) {
1675 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1677 if ($filetype == 'audio') {
1678 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1679 } elseif ($filetype == 'video') {
1680 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1681 // PeerTube audio-only track
1682 if ($height === 0) {
1686 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1687 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1688 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1689 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1691 // For Torrent links we always store the highest resolution
1692 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1696 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1697 } elseif ($mediatype == 'application/x-mpegURL') {
1698 // PeerTube exception, actual video link is in the tags of this URL element
1699 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1703 return array_values($attachments);
1707 * Fetches data from the object part of an activity
1709 * @param array $object
1711 * @return array|bool Object data or FALSE if $object does not contain @id element
1712 * @throws \Exception
1714 private static function processObject(array $object)
1716 if (!JsonLD::fetchElement($object, '@id')) {
1721 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1722 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1723 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1725 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1726 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1727 $object_data['reply-to-id'] = $object_data['id'];
1729 // On activities the "reply to" is the id of the object it refers to
1730 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1731 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1732 if (!empty($object_id)) {
1733 $object_data['reply-to-id'] = $object_id;
1737 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1738 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1739 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1740 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1741 $object_data['reply-to-id'] = $replyToId;
1745 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1746 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1748 if (empty($object_data['updated'])) {
1749 $object_data['updated'] = $object_data['published'];
1752 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1753 $object_data['published'] = $object_data['updated'];
1756 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1757 if (empty($actor)) {
1758 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1761 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1762 $location = JsonLD::fetchElement($location, 'location', '@value');
1764 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1765 // down to HTML and then finally format to plaintext.
1766 $location = Markdown::convert($location);
1767 $location = BBCode::toPlaintext($location);
1770 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1771 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1772 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1773 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1774 $object_data['actor'] = $object_data['author'] = $actor;
1775 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1776 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1777 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1778 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1779 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1780 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1781 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1782 $object_data = self::getSource($object, $object_data);
1783 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1784 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1785 $object_data['location'] = $location;
1786 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1787 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1788 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1789 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1790 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1791 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1792 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1793 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1794 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1795 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1796 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1798 // Special treatment for Hubzilla links
1799 if (is_array($object_data['alternate-url'])) {
1800 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1802 if (!is_string($object_data['alternate-url'])) {
1803 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1807 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1808 $object_data['alternate-url'] = null;
1811 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1812 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1813 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1816 // For page types we expect that the alternate url posts to some page.
1817 // So we add this to the attachments if it differs from the id.
1818 // Currently only Lemmy is using the page type.
1819 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1820 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1821 $object_data['alternate-url'] = null;
1824 if ($object_data['object_type'] == 'as:Question') {
1825 $object_data['question'] = self::processQuestion($object);
1828 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1829 $receivers = $reception_types = [];
1830 foreach ($receiverdata as $key => $data) {
1831 $receivers[$key] = $data['uid'];
1832 $reception_types[$data['uid']] = $data['type'] ?? 0;
1835 $object_data['receiver_urls'] = self::getReceiverURL($object);
1836 $object_data['receiver'] = $receivers;
1837 $object_data['reception_type'] = $reception_types;
1839 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1840 unset($object_data['receiver'][-1]);
1841 unset($object_data['reception_type'][-1]);
1843 return $object_data;