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') ?? '';
100 $apcontact = APContact::getByURL($actor);
102 if (empty($apcontact)) {
103 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
105 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
106 self::processRelayPost($ldactivity, $actor);
109 APContact::unmarkForArchival($apcontact);
112 $http_signer = HTTPSignature::getSigner($body, $header);
113 if ($http_signer === false) {
114 Logger::warning('Invalid HTTP signature, message will be discarded.');
116 } elseif (empty($http_signer)) {
117 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
120 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
123 $signer = [$http_signer];
125 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
127 if (LDSignature::isSigned($activity)) {
128 $ld_signer = LDSignature::getSigner($activity);
129 if (empty($ld_signer)) {
130 Logger::info('Invalid JSON-LD signature from ' . $actor);
131 } elseif ($ld_signer != $http_signer) {
132 $signer[] = $ld_signer;
134 if (!empty($ld_signer && ($actor == $http_signer))) {
135 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
136 $trust_source = true;
137 } elseif (!empty($ld_signer)) {
138 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
139 $trust_source = true;
140 } elseif ($actor == $http_signer) {
141 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
142 $trust_source = true;
144 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
145 $trust_source = false;
147 } elseif ($actor == $http_signer) {
148 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
149 $trust_source = true;
151 Logger::info('No JSON-LD signature, different actor.');
152 $trust_source = false;
155 $fetchQueue = new FetchQueue();
156 self::processActivity($fetchQueue, $ldactivity, $body, $uid, $trust_source, true, $signer);
157 $fetchQueue->process();
161 * Process incoming posts from relays
163 * @param array $activity
164 * @param string $actor
167 private static function processRelayPost(array $activity, string $actor)
169 $type = JsonLD::fetchElement($activity, '@type');
171 Logger::info('Empty type', ['activity' => $activity]);
175 if ($type != 'as:Announce') {
176 Logger::info('Not an announcement', ['activity' => $activity]);
180 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
181 if (empty($object_id)) {
182 Logger::info('No object id found', ['activity' => $activity]);
186 $contact = Contact::getByURL($actor);
187 if (empty($contact)) {
188 Logger::info('Relay contact not found', ['actor' => $actor]);
192 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
193 Logger::notice('Relay is no sharer', ['actor' => $actor]);
197 Logger::info('Got relayed message id', ['id' => $object_id]);
199 $item_id = Item::searchByLink($object_id);
201 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
205 $fetchQueue = new FetchQueue();
207 $id = Processor::fetchMissingActivity($fetchQueue, $object_id, [], $actor, self::COMPLETION_RELAY);
209 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
213 $fetchQueue->process();
215 $item_id = Item::searchByLink($object_id);
217 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
219 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
224 * Fetches the object type for a given object id
226 * @param array $activity
227 * @param string $object_id Object ID of the the provided object
228 * @param integer $uid User ID
230 * @return string with object type or NULL
231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
232 * @throws \ImagickException
234 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
236 if (!empty($activity['as:object'])) {
237 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
238 if (!empty($object_type)) {
243 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
244 // We just assume "note" since it doesn't make a difference for the further processing
248 $profile = APContact::getByURL($object_id);
249 if (!empty($profile['type'])) {
250 APContact::unmarkForArchival($profile);
251 return 'as:' . $profile['type'];
254 $data = ActivityPub::fetchContent($object_id, $uid);
256 $object = JsonLD::compact($data);
257 $type = JsonLD::fetchElement($object, '@type');
267 * Prepare the object array
269 * @param array $activity Array with activity data
270 * @param integer $uid User ID
271 * @param boolean $push Message had been pushed to our system
272 * @param boolean $trust_source Do we trust the source?
274 * @return array with object data
275 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
276 * @throws \ImagickException
278 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
280 $id = JsonLD::fetchElement($activity, '@id');
281 if (!empty($id) && !$trust_source) {
282 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
284 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
285 if (!empty($fetched_activity)) {
286 $object = JsonLD::compact($fetched_activity);
287 $fetched_id = JsonLD::fetchElement($object, '@id');
288 if ($fetched_id == $id) {
289 Logger::info('Activity had been fetched successfully', ['id' => $id]);
290 $trust_source = true;
293 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
296 Logger::info('Activity could not been fetched', ['id' => $id]);
300 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
302 Logger::info('Empty actor', ['activity' => $activity]);
306 $type = JsonLD::fetchElement($activity, '@type');
308 // Fetch all receivers from to, cc, bto and bcc
309 $receiverdata = self::getReceivers($activity, $actor);
310 $receivers = $reception_types = [];
311 foreach ($receiverdata as $key => $data) {
312 $receivers[$key] = $data['uid'];
313 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
316 $urls = self::getReceiverURL($activity);
318 // When it is a delivery to a personal inbox we add that user to the receivers
320 $additional = [$uid => $uid];
321 $receivers = array_replace($receivers, $additional);
322 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]))) {
323 $reception_types[$uid] = self::TARGET_BCC;
324 $owner = User::getOwnerDataById($uid);
325 if (!empty($owner['url'])) {
326 $urls['as:bcc'][] = $owner['url'];
331 // We possibly need some user to fetch private content,
332 // so we fetch one out of the receivers if no uid is provided.
333 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
335 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
336 if (empty($object_id)) {
337 Logger::info('No object found');
341 if (!is_string($object_id)) {
342 Logger::info('Invalid object id', ['object' => $object_id]);
346 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
348 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
349 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
350 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
352 $type = $object_type;
353 $activity = JsonLD::compact($data);
355 // Some variables need to be refetched since the activity changed
356 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
357 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
358 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
362 // Any activities on account types must not be altered
363 if (in_array($object_type, self::ACCOUNT_TYPES)) {
365 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
366 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
367 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
368 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
369 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
370 $object_data['push'] = $push;
371 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
372 // Fetch the content only on activities where this matters
373 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
374 // Always fetch on "Announce"
375 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
376 if (empty($object_data)) {
377 Logger::info("Object data couldn't be processed");
381 $object_data['object_id'] = $object_id;
383 if ($type == 'as:Announce') {
384 $object_data['push'] = false;
386 $object_data['push'] = $push;
389 // Test if it is an answer to a mail
390 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
391 $object_data['directmessage'] = true;
393 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
395 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
396 // Create a mostly empty array out of the activity data (instead of the object).
397 // This way we later don't have to check for the existence of each individual array element.
398 $object_data = self::processObject($activity);
399 $object_data['name'] = $type;
400 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
401 $object_data['object_id'] = $object_id;
402 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
403 $object_data['push'] = $push;
404 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
406 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
407 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
408 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
409 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
410 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
411 $object_data['push'] = $push;
414 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
415 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
416 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
417 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
418 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
419 $object_data['push'] = $push;
421 // An Undo is done on the object of an object, so we need that type as well
422 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
423 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
427 $object_data = self::addActivityFields($object_data, $activity);
429 if (empty($object_data['object_type'])) {
430 $object_data['object_type'] = $object_type;
433 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
434 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
435 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
439 $object_data['type'] = $type;
440 $object_data['actor'] = $actor;
441 $object_data['item_receiver'] = $receivers;
442 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
443 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
445 $author = $object_data['author'] ?? $actor;
446 if (!empty($author) && !empty($object_data['id'])) {
447 $author_host = parse_url($author, PHP_URL_HOST);
448 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
449 if ($author_host == $id_host) {
450 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
452 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
453 $trust_source = false;
457 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
463 * Fetches the first user id from the receiver array
465 * @param array $receivers Array with receivers
466 * @return integer user id;
468 public static function getFirstUserFromReceivers(array $receivers): int
470 foreach ($receivers as $receiver) {
471 if (!empty($receiver)) {
479 * Processes the activity object
481 * @param FetchQueue $fetchQueue
482 * @param array $activity Array with activity data
483 * @param string $body The unprocessed body
484 * @param int|null $uid User ID
485 * @param boolean $trust_source Do we trust the source?
486 * @param boolean $push Message had been pushed to our system
487 * @param array $signer The signer of the post
488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 * @throws \ImagickException
491 public static function processActivity(FetchQueue $fetchQueue, array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
493 $type = JsonLD::fetchElement($activity, '@type');
495 Logger::info('Empty type', ['activity' => $activity]);
499 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
500 Logger::info('Empty object', ['activity' => $activity]);
504 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
506 Logger::info('Empty actor', ['activity' => $activity]);
510 if (is_array($activity['as:object'])) {
511 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
516 // Test the provided signatures against the actor and "attributedTo"
518 if (!empty($attributed_to) && !empty($actor)) {
519 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
521 $trust_source = in_array($actor, $signer);
525 // $trust_source is called by reference and is set to true if the content was retrieved successfully
526 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
527 if (empty($object_data)) {
528 Logger::info('No object data found', ['activity' => $activity]);
532 // Lemmy is announcing activities.
533 // We are changing the announces into regular activities.
534 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
535 $type = $object_data['type'];
538 if (!$trust_source) {
539 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
543 if (!empty($body) && empty($object_data['raw'])) {
544 $object_data['raw'] = $body;
547 // Internal flag for thread completion. See Processor.php
548 if (!empty($activity['thread-completion'])) {
549 $object_data['thread-completion'] = $activity['thread-completion'];
552 if (!empty($activity['completion-mode'])) {
553 $object_data['completion-mode'] = $activity['completion-mode'];
556 if (!empty($activity['thread-children-type'])) {
557 $object_data['thread-children-type'] = $activity['thread-children-type'];
560 // Internal flag for posts that arrived via relay
561 if (!empty($activity['from-relay'])) {
562 $object_data['from-relay'] = $activity['from-relay'];
565 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
566 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
571 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
572 $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
573 ActivityPub\Processor::postItem($object_data, $item);
574 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
575 // Unhandled Peertube activity
577 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
582 if (in_array($object_data['object_type'], ['as:Event'])) {
583 $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
584 ActivityPub\Processor::postItem($object_data, $item);
586 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
591 if ($object_data['object_type'] == 'as:tag') {
592 ActivityPub\Processor::addTag($object_data);
593 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
594 ActivityPub\Processor::addToFeaturedCollection($object_data);
595 } elseif ($object_data['object_type'] == '') {
596 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
598 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
603 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
604 $object_data['thread-completion'] = Contact::getIdForURL($actor);
605 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
607 $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
612 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
613 ActivityPub\Processor::postItem($object_data, $item);
615 $announce_object_data = self::processObject($activity);
616 $announce_object_data['name'] = $type;
617 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
618 $announce_object_data['object_id'] = $object_data['object_id'];
619 $announce_object_data['object_type'] = $object_data['object_type'];
620 $announce_object_data['push'] = $push;
623 $announce_object_data['raw'] = $body;
626 ActivityPub\Processor::createActivity($fetchQueue, $announce_object_data, Activity::ANNOUNCE);
628 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
633 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
634 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::LIKE);
635 } elseif ($object_data['object_type'] == '') {
636 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
638 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
643 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
644 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::DISLIKE);
645 } elseif ($object_data['object_type'] == '') {
646 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
648 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
652 case 'as:TentativeAccept':
653 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
654 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTENDMAYBE);
656 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
661 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
662 ActivityPub\Processor::updateItem($fetchQueue, $object_data);
663 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
664 ActivityPub\Processor::updatePerson($object_data);
665 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
666 // Unhandled Peertube activity
668 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
673 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
674 ActivityPub\Processor::deleteItem($object_data);
675 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
676 ActivityPub\Processor::deletePerson($object_data);
677 } elseif ($object_data['object_type'] == '') {
678 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
680 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
685 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
686 ActivityPub\Processor::blockAccount($object_data);
688 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
693 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
694 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
695 } elseif ($object_data['object_type'] == '') {
696 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
698 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
703 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
704 ActivityPub\Processor::followUser($object_data);
705 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
706 $object_data['reply-to-id'] = $object_data['object_id'];
707 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::FOLLOW);
709 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
714 if ($object_data['object_type'] == 'as:Follow') {
715 ActivityPub\Processor::acceptFollowUser($object_data);
716 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
717 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTEND);
719 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
724 if ($object_data['object_type'] == 'as:Follow') {
725 ActivityPub\Processor::rejectFollowUser($object_data);
726 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
727 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTENDNO);
729 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
734 if (($object_data['object_type'] == 'as:Follow') &&
735 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
736 ActivityPub\Processor::undoFollowUser($object_data);
737 } elseif (($object_data['object_type'] == 'as:Follow') &&
738 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
739 ActivityPub\Processor::undoActivity($object_data);
740 } elseif (($object_data['object_type'] == 'as:Accept') &&
741 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
742 ActivityPub\Processor::rejectFollowUser($object_data);
743 } elseif (($object_data['object_type'] == 'as:Block') &&
744 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
745 ActivityPub\Processor::unblockAccount($object_data);
746 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
747 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
748 ActivityPub\Processor::undoActivity($object_data);
749 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
750 empty($object_data['object_object_type'])) {
751 // We cannot detect the target object. So we can ignore it.
752 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
753 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
754 // Unhandled Peertube activity
756 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
761 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
762 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::VIEW);
763 } elseif ($object_data['object_type'] == '') {
764 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
766 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
770 case 'litepub:EmojiReact':
771 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
772 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::EMOJIREACT);
773 } elseif ($object_data['object_type'] == '') {
774 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
776 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
781 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
782 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
788 * Stores unhandled or unknown Activities as a file
790 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
791 * @param string $type Activity type
792 * @param array $object_data Preprocessed array that is generated out of the received activity
793 * @param array $activity Array with activity data
794 * @param string $body The unprocessed body
795 * @param integer $uid User ID
796 * @param boolean $trust_source Do we trust the source?
797 * @param boolean $push Message had been pushed to our system
798 * @param array $signer The signer of the post
801 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 = [])
803 if (!DI::config()->get('debug', 'ap_log_unknown')) {
807 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
809 if (!empty($object_data['object_type'])) {
810 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
813 if (!empty($object_data['object_object_type'])) {
814 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
817 $tempfile = tempnam(System::getTempPath(), $file);
818 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));
819 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
823 * Fetch a user id from an activity array
825 * @param array $activity
826 * @param string $actor
828 * @return int user id
830 public static function getBestUserForActivity(array $activity): int
833 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
835 $receivers = self::getReceivers($activity, $actor);
836 foreach ($receivers as $receiver) {
837 if ($receiver['type'] == self::TARGET_GLOBAL) {
840 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
841 $uid = $receiver['uid'];
845 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
847 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
848 if (!empty($contact['uid'])) {
849 $uid = $contact['uid'];
856 // @TODO Missing documentation
857 public static function getReceiverURL(array $activity): array
861 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
862 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
863 if (empty($receiver_list)) {
867 foreach ($receiver_list as $receiver) {
868 if ($receiver == self::PUBLIC_COLLECTION) {
869 $receiver = ActivityPub::PUBLIC_COLLECTION;
871 $urls[$element][] = $receiver;
879 * Fetch the receiver list from an activity array
881 * @param array $activity
882 * @param string $actor
884 * @param boolean $fetch_unlisted
886 * @return array with receivers (user id)
889 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
891 $reply = $receivers = $profile = [];
893 // When it is an answer, we inherite the receivers from the parent
894 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
895 if (!empty($replyto)) {
898 // Fix possibly wrong item URI (could be an answer to a plink uri)
899 $fixedReplyTo = Item::getURIByLink($replyto);
900 if (!empty($fixedReplyTo)) {
901 $reply[] = $fixedReplyTo;
905 // Fetch all posts that refer to the object id
906 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
907 if (!empty($object_id)) {
908 $reply[] = $object_id;
911 if (!empty($reply)) {
912 $parents = Post::select(['uid'], ['uri' => $reply]);
913 while ($parent = Post::fetch($parents)) {
914 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
916 DBA::close($parents);
919 if (!empty($actor)) {
920 $profile = APContact::getByURL($actor);
921 $followers = $profile['followers'] ?? '';
922 $is_forum = ($actor['type'] ?? '') == 'Group';
923 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
925 Logger::info('Empty actor', ['activity' => $activity]);
930 // We have to prevent false follower assumptions upon thread completions
931 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
933 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
934 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
935 if (empty($receiver_list)) {
939 foreach ($receiver_list as $receiver) {
940 if ($receiver == self::PUBLIC_COLLECTION) {
941 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
944 // Add receiver "-1" for unlisted posts
945 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
946 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
949 // Fetch the receivers for the public and the followers collection
950 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
951 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
955 // Fetching all directly addressed receivers
956 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
957 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
958 if (!DBA::isResult($contact)) {
962 // Check if the potential receiver is following the actor
963 // Exception: The receiver is targetted via "to" or this is a comment
964 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
965 $networks = Protocol::FEDERATED;
966 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
967 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
969 // Forum posts are only accepted from forum contacts
970 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
971 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
974 if (!DBA::exists('contact', $condition)) {
979 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
980 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
983 $type = self::TARGET_TO;
986 $type = self::TARGET_CC;
989 $type = self::TARGET_BTO;
992 $type = self::TARGET_BCC;
996 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1001 self::switchContacts($receivers, $actor);
1007 * Fetch the receiver list of a given actor
1009 * @param string $actor
1010 * @param array $tags
1011 * @param array $receivers
1012 * @param integer $target_type
1013 * @param array $profile
1015 * @return array with receivers (user id)
1016 * @throws \Exception
1018 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1020 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1021 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1023 if (!empty($profile['uri-id'])) {
1024 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1025 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1026 while ($contact = DBA::fetch($contacts)) {
1027 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1028 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1031 DBA::close($contacts);
1033 // This part will only be called while post update 1426 wasn't finished
1034 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1035 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1036 while ($contact = DBA::fetch($contacts)) {
1037 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1038 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1041 DBA::close($contacts);
1043 // The queries are split because of performance issues
1044 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1045 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1046 while ($contact = DBA::fetch($contacts)) {
1047 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1048 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1051 DBA::close($contacts);
1057 * Tests if the contact is a valid receiver for this actor
1059 * @param array $contact
1060 * @param array $tags
1062 * @return bool with receivers (user id)
1063 * @throws \Exception
1065 private static function isValidReceiverForActor(array $contact, array $tags): bool
1067 // Are we following the contact? Then this is a valid receiver
1068 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1072 // When the possible receiver isn't a community, then it is no valid receiver
1073 $owner = User::getOwnerDataById($contact['uid']);
1074 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1078 // Is the community account tagged?
1079 foreach ($tags as $tag) {
1080 if ($tag['type'] != 'Mention') {
1084 if (Strings::compareLink($tag['href'], $owner['url'])) {
1093 * Switches existing contacts to ActivityPub
1095 * @param integer $cid Contact ID
1096 * @param integer $uid User ID
1097 * @param string $url Profile URL
1099 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1100 * @throws \ImagickException
1102 public static function switchContact(int $cid, int $uid, string $url)
1104 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1105 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1109 if (Contact::updateFromProbe($cid)) {
1110 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1113 // Send a new follow request to be sure that the connection still exists
1114 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1115 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1116 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1121 * @TODO Fix documentation and type-hints
1126 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1127 * @throws \ImagickException
1129 private static function switchContacts($receivers, $actor)
1131 if (empty($actor)) {
1135 foreach ($receivers as $receiver) {
1136 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1137 if (DBA::isResult($contact)) {
1138 self::switchContact($contact['id'], $receiver['uid'], $actor);
1141 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1142 if (DBA::isResult($contact)) {
1143 self::switchContact($contact['id'], $receiver['uid'], $actor);
1149 * @TODO Fix documentation and type-hints
1151 * @param $object_data
1152 * @param array $activity
1156 private static function addActivityFields($object_data, array $activity)
1158 if (!empty($activity['published']) && empty($object_data['published'])) {
1159 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1162 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1163 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1166 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1167 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1169 if (!empty($object_data['object_id'])) {
1170 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1171 $objectId = Item::getURIByLink($object_data['object_id']);
1172 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1173 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1174 $object_data['object_id'] = $objectId;
1178 return $object_data;
1182 * Fetches the object data from external ressources if needed
1184 * @param string $object_id Object ID of the the provided object
1185 * @param array $object The provided object array
1186 * @param boolean $trust_source Do we trust the provided object?
1187 * @param integer $uid User ID for the signature that we use to fetch data
1189 * @return array|false with trusted and valid object data
1190 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1191 * @throws \ImagickException
1193 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1195 // By fetching the type we check if the object is complete.
1196 $type = JsonLD::fetchElement($object, '@type');
1198 if (!$trust_source || empty($type)) {
1199 $data = ActivityPub::fetchContent($object_id, $uid);
1200 if (!empty($data)) {
1201 $object = JsonLD::compact($data);
1202 Logger::info('Fetched content for ' . $object_id);
1204 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1206 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1207 if (!DBA::isResult($item)) {
1208 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1211 Logger::info('Using already stored item for url ' . $object_id);
1212 $data = ActivityPub\Transmitter::createNote($item);
1213 $object = JsonLD::compact($data);
1216 $id = JsonLD::fetchElement($object, '@id');
1218 Logger::info('Empty id');
1222 if ($id != $object_id) {
1223 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1227 Logger::info('Using original object for url ' . $object_id);
1230 $type = JsonLD::fetchElement($object, '@type');
1232 Logger::info('Empty type');
1236 // Lemmy is resharing "create" activities instead of content
1237 // We fetch the content from the activity.
1238 if (in_array($type, ['as:Create'])) {
1239 $object = $object['as:object'];
1240 $type = JsonLD::fetchElement($object, '@type');
1242 Logger::info('Empty type');
1245 $object_data = self::processObject($object);
1248 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1249 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1250 $object_data = self::processObject($object);
1252 if (!empty($data)) {
1253 $object_data['raw'] = json_encode($data);
1255 return $object_data;
1258 if ($type == 'as:Announce') {
1259 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1260 if (empty($object_id) || !is_string($object_id)) {
1263 return self::fetchObject($object_id, [], false, $uid);
1266 Logger::info('Unhandled object type: ' . $type);
1271 * Converts the language element (Used by Peertube)
1273 * @param array $languages
1274 * @return array Languages
1276 public static function processLanguages(array $languages): array
1278 if (empty($languages)) {
1282 $language_list = [];
1284 foreach ($languages as $language) {
1285 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1286 $language_list[$language['_:identifier']] = $language['as:name'];
1289 return $language_list;
1293 * Convert tags from JSON-LD format into a simplified format
1295 * @param array $tags Tags in JSON-LD format
1297 * @return array with tags in a simplified format
1299 public static function processTags(array $tags): array
1303 foreach ($tags as $tag) {
1308 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1309 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1310 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1312 if (empty($element['type'])) {
1316 if (empty($element['href'])) {
1317 $element['href'] = $element['name'];
1320 $taglist[] = $element;
1326 * Convert emojis from JSON-LD format into a simplified format
1328 * @param array $emojis
1329 * @return array with emojis in a simplified format
1331 private static function processEmojis(array $emojis): array
1335 foreach ($emojis as $emoji) {
1336 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1340 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1341 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1344 $emojilist[] = $element;
1351 * Convert attachments from JSON-LD format into a simplified format
1353 * @param array $attachments Attachments in JSON-LD format
1355 * @return array Attachments in a simplified format
1357 private static function processAttachments(array $attachments): array
1361 // Removes empty values
1362 $attachments = array_filter($attachments);
1364 foreach ($attachments as $attachment) {
1365 switch (JsonLD::fetchElement($attachment, '@type')) {
1370 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1371 foreach ($urls as $url) {
1372 // Single scalar URL case
1373 if (is_string($url)) {
1378 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1379 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1380 if (Strings::startsWith($mediaType, 'image')) {
1389 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1390 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1392 'image' => $pageImage,
1396 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1397 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1398 $imagePreviewUrl = null;
1400 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1401 $imageVariants = [];
1402 $previewVariants = [];
1403 foreach ($urls as $url) {
1404 // Scalar URL, no discrimination possible
1405 if (is_string($url)) {
1406 $imageFullUrl = $url;
1410 // Not sure what to do with a different Link media type than the base Image, we skip
1411 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1415 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1417 // Default URL choice if no discriminating width is provided
1418 $imageFullUrl = $href ?? $imageFullUrl;
1420 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1422 if ($href && $width) {
1423 $imageVariants[$width] = $href;
1424 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1425 $previewVariants[abs(632 - $width)] = $href;
1429 if ($imageVariants) {
1430 // Taking the maximum size image
1431 ksort($imageVariants);
1432 $imageFullUrl = array_pop($imageVariants);
1434 // Taking the minimum number distance to the target distance
1435 ksort($previewVariants);
1436 $imagePreviewUrl = array_shift($previewVariants);
1439 unset($imageVariants);
1440 unset($previewVariants);
1444 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1445 'mediaType' => $mediaType,
1446 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1447 'url' => $imageFullUrl,
1448 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1453 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1454 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1455 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1456 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1457 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1458 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1459 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1468 * Convert questions from JSON-LD format into a simplified format
1470 * @param array $object
1472 * @return array Questions in a simplified format
1474 private static function processQuestion(array $object): array
1478 if (!empty($object['as:oneOf'])) {
1479 $question['multiple'] = false;
1480 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1481 } elseif (!empty($object['as:anyOf'])) {
1482 $question['multiple'] = true;
1483 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1488 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1489 if (!empty($closed)) {
1490 $question['end-time'] = $closed;
1492 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1495 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1496 $question['options'] = [];
1500 foreach ($options as $option) {
1501 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1505 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1507 if (empty($option['as:replies'])) {
1511 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1513 $question['options'][] = ['name' => $name, 'replies' => $replies];
1515 $voters += (int)$replies;
1518 // For single choice question we can count the number of voters if not provided (like with Misskey)
1519 if (empty($question['voters']) && !$question['multiple']) {
1520 $question['voters'] = $voters;
1527 * Fetch the original source or content with the "language" Markdown or HTML
1529 * @param array $object
1530 * @param array $object_data
1532 * @return array Object data (?)
1533 * @throws \Exception
1535 private static function getSource(array $object, array $object_data): array
1537 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1538 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1539 if (!empty($object_data['source'])) {
1540 return $object_data;
1543 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1544 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1545 if (!empty($object_data['source'])) {
1546 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1547 return $object_data;
1550 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1551 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1552 if (!empty($object_data['source'])) {
1553 $object_data['source'] = HTML::toBBCode($object_data['source']);
1554 return $object_data;
1557 return $object_data;
1561 * Extracts a potential alternate URL from a list of additional URL elements
1563 * @param array $urls
1566 private static function extractAlternateUrl(array $urls): string
1569 foreach ($urls as $key => $url) {
1570 // Not a list but a single URL element
1571 if (!is_numeric($key)) {
1575 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1579 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1584 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1585 if (empty($mediatype)) {
1589 if ($mediatype == 'text/html') {
1590 $alternateUrl = $href;
1594 return $alternateUrl;
1598 * Check if the "as:url" element is an array with multiple links
1599 * This is the case with audio and video posts.
1600 * Then the links are added as attachments
1602 * @param array $urls The object URL list
1603 * @return array an array of attachments
1605 private static function processAttachmentUrls(array $urls): array
1608 foreach ($urls as $key => $url) {
1609 // Not a list but a single URL element
1610 if (!is_numeric($key)) {
1614 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1618 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1623 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1624 if (empty($mediatype)) {
1628 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1630 if ($filetype == 'audio') {
1631 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1632 } elseif ($filetype == 'video') {
1633 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1634 // PeerTube audio-only track
1635 if ($height === 0) {
1639 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1640 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1641 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1642 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1644 // For Torrent links we always store the highest resolution
1645 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1649 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1650 } elseif ($mediatype == 'application/x-mpegURL') {
1651 // PeerTube exception, actual video link is in the tags of this URL element
1652 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1656 return array_values($attachments);
1660 * Fetches data from the object part of an activity
1662 * @param array $object
1664 * @return array|bool Object data or FALSE if $object does not contain @id element
1665 * @throws \Exception
1667 private static function processObject(array $object)
1669 if (!JsonLD::fetchElement($object, '@id')) {
1674 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1675 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1676 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1678 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1679 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1680 $object_data['reply-to-id'] = $object_data['id'];
1682 // On activities the "reply to" is the id of the object it refers to
1683 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1684 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1685 if (!empty($object_id)) {
1686 $object_data['reply-to-id'] = $object_id;
1690 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1691 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1692 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1693 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1694 $object_data['reply-to-id'] = $replyToId;
1698 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1699 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1701 if (empty($object_data['updated'])) {
1702 $object_data['updated'] = $object_data['published'];
1705 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1706 $object_data['published'] = $object_data['updated'];
1709 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1710 if (empty($actor)) {
1711 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1714 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1715 $location = JsonLD::fetchElement($location, 'location', '@value');
1717 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1718 // down to HTML and then finally format to plaintext.
1719 $location = Markdown::convert($location);
1720 $location = BBCode::toPlaintext($location);
1723 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1724 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1725 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1726 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1727 $object_data['actor'] = $object_data['author'] = $actor;
1728 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1729 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1730 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1731 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1732 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1733 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1734 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1735 $object_data = self::getSource($object, $object_data);
1736 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1737 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1738 $object_data['location'] = $location;
1739 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1740 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1741 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1742 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1743 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1744 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1745 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1746 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1747 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1748 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1749 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1751 // Special treatment for Hubzilla links
1752 if (is_array($object_data['alternate-url'])) {
1753 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1755 if (!is_string($object_data['alternate-url'])) {
1756 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1760 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1761 $object_data['alternate-url'] = null;
1764 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1765 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1766 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1769 // For page types we expect that the alternate url posts to some page.
1770 // So we add this to the attachments if it differs from the id.
1771 // Currently only Lemmy is using the page type.
1772 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1773 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1774 $object_data['alternate-url'] = null;
1777 if ($object_data['object_type'] == 'as:Question') {
1778 $object_data['question'] = self::processQuestion($object);
1781 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1782 $receivers = $reception_types = [];
1783 foreach ($receiverdata as $key => $data) {
1784 $receivers[$key] = $data['uid'];
1785 $reception_types[$data['uid']] = $data['type'] ?? 0;
1788 $object_data['receiver_urls'] = self::getReceiverURL($object);
1789 $object_data['receiver'] = $receivers;
1790 $object_data['reception_type'] = $reception_types;
1792 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1793 unset($object_data['receiver'][-1]);
1794 unset($object_data['reception_type'][-1]);
1796 // Common object data:
1799 // @context, type, actor, signature, mediaType, duration, replies, icon
1801 // Also missing: (Defined in the standard, but currently unused)
1802 // audience, preview, endTime, startTime, image
1807 // contentMap, announcement_count, announcements, context_id, likes, like_count
1808 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1813 // category, licence, language, commentsEnabled
1816 // views, waitTranscoding, state, support, subtitleLanguage
1817 // likes, dislikes, shares, comments
1819 return $object_data;