3 * @copyright Copyright (C) 2010-2023, 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;
31 use Friendica\Core\Worker;
32 use Friendica\Database\Database;
34 use Friendica\Model\Contact;
35 use Friendica\Model\APContact;
36 use Friendica\Model\Item;
37 use Friendica\Model\Post;
38 use Friendica\Model\User;
39 use Friendica\Protocol\Activity;
40 use Friendica\Protocol\ActivityPub;
41 use Friendica\Util\DateTimeFormat;
42 use Friendica\Util\HTTPSignature;
43 use Friendica\Util\JsonLD;
44 use Friendica\Util\LDSignature;
45 use Friendica\Util\Network;
46 use Friendica\Util\Strings;
49 * ActivityPub Receiver Protocol class
54 * Check what this is meant to do:
63 const PUBLIC_COLLECTION = 'as:Public';
64 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
65 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
66 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept', 'as:View', 'as:Read', 'litepub:EmojiReact'];
68 const TARGET_UNKNOWN = 0;
73 const TARGET_FOLLOWER = 5;
74 const TARGET_ANSWER = 6;
75 const TARGET_GLOBAL = 7;
76 const TARGET_AUDIENCE = 8;
78 const COMPLETION_NONE = 0;
79 const COMPLETION_ANNOUNCE = 1;
80 const COMPLETION_RELAY = 2;
81 const COMPLETION_MANUAL = 3;
82 const COMPLETION_AUTO = 4;
83 const COMPLETION_ASYNC = 5;
86 * Checks incoming message from the inbox
88 * @param string $body Body string
89 * @param array $header Header lines
90 * @param integer $uid User ID
94 public static function processInbox(string $body, array $header, int $uid)
96 $activity = json_decode($body, true);
97 if (empty($activity)) {
98 Logger::warning('Invalid body.');
102 $ldactivity = JsonLD::compact($activity);
104 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
106 $apcontact = APContact::getByURL($actor);
108 if (empty($apcontact)) {
109 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
111 } elseif (APContact::isRelay($apcontact) && self::isRelayPost($ldactivity)) {
112 self::processRelayPost($ldactivity, $actor);
115 APContact::unmarkForArchival($apcontact);
118 $sig_contact = HTTPSignature::getKeyIdContact($header);
119 if (APContact::isRelay($sig_contact) && self::isRelayPost($ldactivity)) {
120 Logger::info('Message from a relay', ['url' => $sig_contact['url']]);
121 self::processRelayPost($ldactivity, $sig_contact['url']);
125 $http_signer = HTTPSignature::getSigner($body, $header);
126 if ($http_signer === false) {
127 Logger::notice('Invalid HTTP signature, message will not be trusted.', ['uid' => $uid, 'actor' => $actor, 'header' => $header, 'body' => $body]);
129 } elseif (empty($http_signer)) {
130 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
133 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
134 $signer = [$http_signer];
137 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
139 if ($http_signer === false) {
140 $trust_source = false;
141 } elseif (LDSignature::isSigned($activity)) {
142 $ld_signer = LDSignature::getSigner($activity);
143 if (empty($ld_signer)) {
144 Logger::info('Invalid JSON-LD signature from ' . $actor);
145 } elseif ($ld_signer != $http_signer) {
146 $signer[] = $ld_signer;
148 if (!empty($ld_signer && ($actor == $http_signer))) {
149 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
150 $trust_source = true;
151 } elseif (!empty($ld_signer)) {
152 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
153 $trust_source = true;
154 } elseif ($actor == $http_signer) {
155 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
156 $trust_source = true;
158 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
159 $trust_source = false;
161 } elseif ($actor == $http_signer) {
162 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
163 $trust_source = true;
165 Logger::info('No JSON-LD signature, different actor.');
166 $trust_source = false;
169 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
173 * Check if the activity is a post rhat can be send via a relay
175 * @param array $activity
178 private static function isRelayPost(array $activity): bool
180 $type = JsonLD::fetchElement($activity, '@type');
185 $object_type = JsonLD::fetchElement($activity, 'as:object', '@type') ?? '';
187 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
188 if (empty($object_id)) {
192 $handle = ($type == 'as:Announce');
194 if (!$handle && in_array($type, ['as:Create', 'as:Update'])) {
195 $handle = in_array($object_type, self::CONTENT_TYPES);
201 * Process incoming posts from relays
203 * @param array $activity
204 * @param string $actor
207 private static function processRelayPost(array $activity, string $actor)
209 $type = JsonLD::fetchElement($activity, '@type');
211 Logger::notice('Empty type', ['activity' => $activity, 'actor' => $actor]);
215 $object_type = JsonLD::fetchElement($activity, 'as:object', '@type') ?? '';
217 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
218 if (empty($object_id)) {
219 Logger::notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]);
223 $contact = Contact::getByURL($actor);
224 if (empty($contact)) {
225 Logger::info('Relay contact not found', ['actor' => $actor]);
229 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
230 Logger::notice('Relay is no sharer', ['actor' => $actor]);
234 Logger::debug('Process post from relay server', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]);
236 $item_id = Item::searchByLink($object_id);
238 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
242 if (!DI::config()->get('system', 'decoupled_receiver')) {
243 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
245 Logger::notice('Relayed message is fetched', ['result' => $id, 'id' => $object_id, 'actor' => $actor]);
247 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
249 } elseif (!Fetch::hasWorker($object_id)) {
250 Logger::notice('Fetching is done by worker.', ['id' => $object_id]);
251 Fetch::add($object_id);
252 $activity['recursion-depth'] = 0;
253 $wid = Worker::add(Worker::PRIORITY_HIGH, 'FetchMissingActivity', $object_id, [], $actor, self::COMPLETION_RELAY);
254 Fetch::setWorkerId($object_id, $wid);
256 Logger::debug('Activity will already be fetched via a worker.', ['url' => $object_id]);
261 * Fetches the object type for a given object id
263 * @param array $activity
264 * @param string $object_id Object ID of the provided object
265 * @param integer $uid User ID
267 * @return string with object type or NULL
268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
269 * @throws \ImagickException
271 public static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
273 if (!empty($activity['as:object'])) {
274 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
275 if (!empty($object_type)) {
280 if (Post::exists(['uri' => $object_id, 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]])) {
281 // We just assume "note" since it doesn't make a difference for the further processing
285 $profile = APContact::getByURL($object_id);
286 if (!empty($profile['type'])) {
287 APContact::unmarkForArchival($profile);
288 return 'as:' . $profile['type'];
291 $data = Processor::fetchCachedActivity($object_id, $uid);
293 $object = JsonLD::compact($data);
294 $type = JsonLD::fetchElement($object, '@type');
304 * Prepare the object array
306 * @param array $activity Array with activity data
307 * @param integer $uid User ID
308 * @param boolean $push Message had been pushed to our system
309 * @param boolean $trust_source Do we trust the source?
310 * @param string $original_actor Actor of the original activity. Used for receiver detection. (Optional)
312 * @return array with object data
313 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
314 * @throws \ImagickException
316 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source, string $original_actor = ''): array
318 $id = JsonLD::fetchElement($activity, '@id');
319 $type = JsonLD::fetchElement($activity, '@type');
320 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
322 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
323 $fetch_id = $object_id;
328 if (!empty($activity['as:object'])) {
329 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
334 if (!empty($id) && !$trust_source) {
335 $fetch_uid = $uid ?: self::getBestUserForActivity($activity, $original_actor);
337 $fetched_activity = Processor::fetchCachedActivity($fetch_id, $fetch_uid);
338 if (!empty($fetched_activity)) {
340 $object = JsonLD::compact($fetched_activity);
342 $fetched_id = JsonLD::fetchElement($object, '@id');
343 $fetched_type = JsonLD::fetchElement($object, '@type');
345 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
346 Logger::info('Activity had been fetched successfully', ['id' => $id]);
347 $trust_source = true;
349 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
350 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
351 $trust_source = true;
352 unset($object['@context']);
353 $activity['as:object'] = $object;
355 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
358 Logger::info('Activity could not been fetched', ['id' => $id]);
362 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
364 Logger::info('Empty actor', ['activity' => $activity]);
368 $type = JsonLD::fetchElement($activity, '@type');
370 // Fetch all receivers from to, cc, bto and bcc
371 $receiverdata = self::getReceivers($activity, $original_actor ?: $actor, [], false, $push || $fetched);
372 $receivers = $reception_types = [];
373 foreach ($receiverdata as $key => $data) {
374 $receivers[$key] = $data['uid'];
375 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
378 $urls = self::getReceiverURL($activity);
380 // When it is a delivery to a personal inbox we add that user to the receivers
382 $additional = [$uid => $uid];
383 $receivers = array_replace($receivers, $additional);
384 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]))) {
385 $reception_types[$uid] = self::TARGET_BCC;
386 $owner = User::getOwnerDataById($uid);
387 if (!empty($owner['url'])) {
388 $urls['as:bcc'][] = $owner['url'];
393 // We possibly need some user to fetch private content,
394 // so we fetch one out of the receivers if no uid is provided.
395 $fetch_uid = $uid ?: self::getBestUserForActivity($activity, $original_actor);
397 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
398 if (empty($object_id)) {
399 Logger::info('No object found');
403 if (!is_string($object_id)) {
404 Logger::info('Invalid object id', ['object' => $object_id]);
408 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
410 // Any activities on account types must not be altered
411 if (in_array($type, ['as:Flag'])) {
413 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
414 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
415 $object_data['object_ids'] = JsonLD::fetchElementArray($activity, 'as:object', '@id');
416 $object_data['content'] = JsonLD::fetchElement($activity, 'as:content', '@type');
417 } elseif (in_array($object_type, self::ACCOUNT_TYPES)) {
419 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
420 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
421 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
422 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
423 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
424 if (!$trust_source && ($type == 'as:Delete')) {
425 $apcontact = APContact::getByURL($object_data['object_id'], true);
426 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
428 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Invite']) || strpos($type, '#emojiReaction')) {
429 // Fetch the content only on activities where this matters
430 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
431 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $fetch_uid);
432 if (empty($object_data)) {
433 Logger::info("Object data couldn't be processed");
437 $object_data['object_id'] = $object_id;
439 // Test if it is a direct message
440 if (self::checkForDirectMessage($object_data, $activity)) {
441 $object_data['directmessage'] = true;
442 } elseif (!empty(JsonLD::fetchElement($activity['as:object'], 'misskey:_misskey_talk'))) {
443 $object_data = self::setChatData($object_data, $receivers);
445 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
446 // Create a mostly empty array out of the activity data (instead of the object).
447 // This way we later don't have to check for the existence of each individual array element.
448 $object_data = self::processObject($activity, $original_actor);
449 $object_data['name'] = $type;
450 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
451 $object_data['object_id'] = $object_id;
452 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
453 } elseif (in_array($type, ['as:Add', 'as:Remove', 'as:Move'])) {
455 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
456 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
457 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
458 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
459 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
462 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
463 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
464 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
465 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
466 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
468 // An Undo is done on the object of an object, so we need that type as well
469 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
470 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
473 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
474 $trust_source = Processor::isActivityGone($object_data['object_id']);
475 if (!$trust_source) {
476 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
481 $object_data['push'] = $push;
483 $object_data = self::addActivityFields($object_data, $activity);
485 if (empty($object_data['object_type'])) {
486 $object_data['object_type'] = $object_type;
489 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience', 'as:attributedTo'] as $element) {
490 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
491 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
495 $object_data['type'] = $type;
496 $object_data['actor'] = $actor;
497 $object_data['item_receiver'] = $receivers;
498 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
499 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
501 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
502 // $author = $object_data['author'] ?? $actor;
503 // if (!empty($author) && !empty($object_data['id'])) {
504 // $author_host = parse_url($author, PHP_URL_HOST);
505 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
506 // if ($author_host == $id_host) {
507 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
509 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
510 // $trust_source = false;
514 $account = Contact::selectFirstAccount(['platform'], ['nurl' => Strings::normaliseLink($actor)]);
515 $platform = $account['platform'] ?? '';
517 Logger::info('Processing', ['type' => $object_data['type'], 'object_type' => $object_data['object_type'], 'id' => $object_data['id'], 'actor' => $actor, 'platform' => $platform]);
523 * Check if the received message is a direct message
525 * @param array $object_data
526 * @param array $activity
529 private static function checkForDirectMessage(array $object_data, array $activity): bool
531 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
535 if ($object_data['id'] != $object_data['reply-to-id']) {
539 if (JsonLD::fetchElement($activity, 'litepub:directMessage')) {
543 if (!empty($object_data['attachments'])) {
547 if (!empty($object_data['receiver_urls']['as:cc']) || empty($object_data['receiver_urls']['as:to'])) {
551 if ((count($object_data['receiver_urls']['as:to']) != 1) || !User::getIdForURL($object_data['receiver_urls']['as:to'][0])) {
556 foreach ($object_data['tags'] as $mention) {
557 if ($mention['type'] != 'Mention') {
560 if (!User::getIdForURL($mention['href'])) {
573 private static function setChatData(array $object_data, array $receivers): array
575 if (count($receivers) != 1) {
579 $user = User::getById(array_key_first($receivers), ['language']);
580 $l10n = DI::l10n()->withLang($user['language']);
581 $object_data['name'] = $l10n->t('Chat');
583 $mail = DBA::selectFirst('mail', ['uri'], ['uid' => array_key_first($receivers), 'title' => $object_data['name']], ['order' => ['id' => true]]);
584 if (!empty($mail['uri'])) {
585 $object_data['reply-to-id'] = $mail['uri'];
588 $object_data['directmessage'] = true;
589 Logger::debug('Got Misskey Chat');
594 * Fetches the first user id from the receiver array
596 * @param array $receivers Array with receivers
597 * @return integer user id;
599 public static function getFirstUserFromReceivers(array $receivers): int
601 foreach ($receivers as $receiver) {
602 if (!empty($receiver)) {
610 * Processes the activity object
612 * @param array $activity Array with activity data
613 * @param string $body The unprocessed body
614 * @param int|null $uid User ID
615 * @param boolean $trust_source Do we trust the source?
616 * @param boolean $push Message had been pushed to our system
617 * @param array $signer The signer of the post
621 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
622 * @throws \ImagickException
624 public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '', int $completion = Receiver::COMPLETION_AUTO): bool
626 $type = JsonLD::fetchElement($activity, '@type');
628 Logger::info('Empty type', ['activity' => $activity]);
632 if (!DI::config()->get('system', 'process_view') && ($type == 'as:View')) {
633 Logger::info('View activities are ignored.', ['signer' => $signer, 'http_signer' => $http_signer]);
637 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
638 Logger::info('Empty object', ['activity' => $activity]);
642 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
644 Logger::info('Empty actor', ['activity' => $activity]);
648 if (is_array($activity['as:object'])) {
649 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
654 // Test the provided signatures against the actor and "attributedTo"
656 if (!empty($attributed_to) && !empty($actor)) {
657 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
659 $trust_source = in_array($actor, $signer);
663 // Lemmy announces activities.
664 // To simplify the further processing, we modify the received object.
665 // For announced "create" activities we remove the middle layer.
666 // For the rest (like, dislike, update, ...) we just process the activity directly.
667 $original_actor = '';
668 $object_type = JsonLD::fetchElement($activity['as:object'] ?? [], '@type');
669 if (($type == 'as:Announce') && !empty($object_type) && !in_array($object_type, self::CONTENT_TYPES) && self::isGroup($actor)) {
670 $object_object_type = JsonLD::fetchElement($activity['as:object']['as:object'] ?? [], '@type');
671 if (in_array($object_type, ['as:Create']) && in_array($object_object_type, self::CONTENT_TYPES)) {
672 Logger::debug('Replace "create" activity with inner object', ['type' => $object_type, 'object_type' => $object_object_type]);
673 $activity['as:object'] = $activity['as:object']['as:object'];
674 } elseif (in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
675 Logger::debug('Change announced activity to activity', ['type' => $object_type]);
676 $original_actor = $actor;
677 $type = $object_type;
678 $activity = $activity['as:object'];
680 Logger::info('Unhandled announced activity', ['type' => $object_type, 'object_type' => $object_object_type]);
684 // $trust_source is called by reference and is set to true if the content was retrieved successfully
685 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source, $original_actor);
686 if (empty($object_data)) {
687 Logger::info('No object data found', ['activity' => $activity]);
691 if (!empty($body) && empty($object_data['raw'])) {
692 $object_data['raw'] = $body;
695 // Internal flag for thread completion. See Processor.php
696 if (!empty($activity['thread-completion'])) {
697 $object_data['thread-completion'] = $activity['thread-completion'];
700 if (!empty($activity['completion-mode'])) {
701 $object_data['completion-mode'] = $activity['completion-mode'];
704 if (!empty($activity['thread-children-type'])) {
705 $object_data['thread-children-type'] = $activity['thread-children-type'];
708 // Internal flag for posts that arrived via relay
709 if (!empty($activity['from-relay'])) {
710 $object_data['from-relay'] = $activity['from-relay'];
713 if ($type == 'as:Announce') {
714 $object_data['object_activity'] = $activity;
717 if (($type == 'as:Create') && $trust_source && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE])) {
718 if (self::hasArrived($object_data['object_id'])) {
719 Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]);
722 self::addArrivedId($object_data['object_id']);
724 if (Queue::exists($object_data['object_id'], $type)) {
725 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
728 } elseif (($type == 'as:Create') && $trust_source && !self::hasArrived($object_data['object_id'])) {
729 self::addArrivedId($object_data['object_id']);
732 $decouple = DI::config()->get('system', 'decoupled_receiver') && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE]) && empty($object_data['directmessage']);
734 if ($decouple && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
735 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
738 if (!$trust_source) {
739 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
743 if (!empty($object_data['entry-id']) && $decouple && ($push || in_array($completion, [self::COMPLETION_RELAY, self::COMPLETION_ASYNC]))) {
744 if (Queue::isProcessable($object_data['entry-id'])) {
745 // We delay by 5 seconds to allow to accumulate all receivers
746 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
747 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
748 $wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
749 Queue::setWorkerId($object_data['entry-id'], $wid);
751 Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]);
756 if (!empty($activity['recursion-depth'])) {
757 $object_data['recursion-depth'] = $activity['recursion-depth'];
760 if (!self::routeActivities($object_data, $type, $push, true, $uid)) {
761 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
762 Queue::remove($object_data);
768 * Checks if the provided actor is a group account
770 * @param string $actor
773 private static function isGroup(string $actor): bool
775 $profile = APContact::getByURL($actor);
776 return ($profile['type'] ?? '') == 'Group';
782 * @param array $object_data
783 * @param string $type
785 * @param bool $fetch_parents
788 * @return boolean Could the activity be routed?
790 public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true, int $uid = 0): bool
794 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
795 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
796 ActivityPub\Processor::postItem($object_data, $item);
797 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
798 // Unhandled Peertube activity
799 Queue::remove($object_data);
800 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
801 ActivityPub\Processor::updatePerson($object_data);
808 if (in_array($object_data['object_type'], ['as:Event'])) {
809 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
810 ActivityPub\Processor::postItem($object_data, $item);
817 if ($object_data['object_type'] == 'as:tag') {
818 ActivityPub\Processor::addTag($object_data);
819 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
820 ActivityPub\Processor::addToFeaturedCollection($object_data);
821 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
822 // We don't have the object here or it is deleted. We ignore this activity.
823 Queue::remove($object_data);
830 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
831 if (!Item::searchByLink($object_data['object_id'], $uid)) {
832 if (ActivityPub\Processor::fetchMissingActivity($object_data['object_id'], [], $object_data['actor'], self::COMPLETION_ANNOUNCE, $uid)) {
833 Logger::debug('Created announced id', ['uid' => $uid, 'id' => $object_data['object_id']]);
834 Queue::remove($object_data);
836 Logger::debug('Announced id was not created', ['uid' => $uid, 'id' => $object_data['object_id']]);
837 Queue::remove($object_data);
841 Logger::info('Announced id already exists', ['uid' => $uid, 'id' => $object_data['object_id']]);
842 Queue::remove($object_data);
845 ActivityPub\Processor::createActivity($object_data, Activity::ANNOUNCE);
846 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
847 // We don't have the object here or it is deleted. We ignore this activity.
848 Queue::remove($object_data);
855 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
856 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
857 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
858 // We don't have the object here or it is deleted. We ignore this activity.
859 Queue::remove($object_data);
866 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
867 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
868 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
869 // We don't have the object here or it is deleted. We ignore this activity.
870 Queue::remove($object_data);
876 case 'as:TentativeAccept':
877 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
878 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
885 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
886 ActivityPub\Processor::updateItem($object_data);
887 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
888 ActivityPub\Processor::updatePerson($object_data);
889 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
890 // Unhandled Peertube activity
891 Queue::remove($object_data);
898 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
899 ActivityPub\Processor::deleteItem($object_data);
900 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
901 ActivityPub\Processor::deletePerson($object_data);
902 } elseif ($object_data['object_type'] == '') {
903 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
904 Queue::remove($object_data);
911 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
912 ActivityPub\Processor::movePerson($object_data);
919 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
920 ActivityPub\Processor::blockAccount($object_data);
927 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
928 ActivityPub\Processor::ReportAccount($object_data);
935 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
936 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
937 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
938 // We don't have the object here or it is deleted. We ignore this activity.
939 Queue::remove($object_data);
946 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
947 ActivityPub\Processor::followUser($object_data);
948 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
949 $object_data['reply-to-id'] = $object_data['object_id'];
950 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
957 if ($object_data['object_type'] == 'as:Follow') {
958 if (!empty($object_data['object_actor'])) {
959 ActivityPub\Processor::acceptFollowUser($object_data);
961 Logger::notice('Unhandled "accept follow" message.', ['object_data' => $object_data]);
963 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
964 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
965 } elseif (!empty($object_data['object_id']) && empty($object_data['object_actor']) && empty($object_data['object_type'])) {
966 // Follow acceptances from gup.pe only contain the object id
967 ActivityPub\Processor::acceptFollowUser($object_data);
974 if ($object_data['object_type'] == 'as:Follow') {
975 ActivityPub\Processor::rejectFollowUser($object_data);
976 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
977 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
984 if (($object_data['object_type'] == 'as:Follow') &&
985 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
986 ActivityPub\Processor::undoFollowUser($object_data);
987 } elseif (($object_data['object_type'] == 'as:Follow') &&
988 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
989 ActivityPub\Processor::undoActivity($object_data);
990 } elseif (($object_data['object_type'] == 'as:Accept') &&
991 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
992 ActivityPub\Processor::rejectFollowUser($object_data);
993 } elseif (($object_data['object_type'] == 'as:Block') &&
994 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
995 ActivityPub\Processor::unblockAccount($object_data);
996 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
997 empty($object_data['object_object_type'])) {
998 // We cannot detect the target object. So we can ignore it.
999 Queue::remove($object_data);
1000 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
1001 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
1002 ActivityPub\Processor::undoActivity($object_data);
1003 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
1004 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
1005 // Unhandled Peertube activity
1006 Queue::remove($object_data);
1007 } elseif (in_array($object_data['object_type'], ['as:Delete'])) {
1008 // We cannot undo deletions, so we just ignore this
1009 Queue::remove($object_data);
1010 } elseif (in_array($object_data['object_object_type'], ['as:Tombstone'])) {
1011 // The object is a tombstone, we ignore any actions on it.
1012 Queue::remove($object_data);
1019 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
1020 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
1021 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
1022 // We don't have the object here or it is deleted. We ignore this activity.
1023 Queue::remove($object_data);
1029 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
1030 ActivityPub\Processor::createActivity($object_data, Activity::READ);
1031 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
1032 // We don't have the object here or it is deleted. We ignore this activity.
1033 Queue::remove($object_data);
1039 case 'litepub:EmojiReact':
1040 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
1041 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
1042 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
1043 // We don't have the object here or it is deleted. We ignore this activity.
1044 Queue::remove($object_data);
1051 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
1058 * Stores unhandled or unknown Activities as a file
1060 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
1061 * @param string $type Activity type
1062 * @param array $object_data Preprocessed array that is generated out of the received activity
1063 * @param array $activity Array with activity data
1064 * @param string $body The unprocessed body
1065 * @param integer $uid User ID
1066 * @param boolean $trust_source Do we trust the source?
1067 * @param boolean $push Message had been pushed to our system
1068 * @param array $signer The signer of the post
1071 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 = [])
1073 if (!DI::config()->get('debug', 'ap_log_unknown')) {
1077 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
1079 if (!empty($object_data['object_type'])) {
1080 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
1083 if (!empty($object_data['object_object_type'])) {
1084 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
1087 $tempfile = tempnam(System::getTempPath(), $file);
1088 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));
1089 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], 'object_object_type' => $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
1093 * Fetch a user id from an activity array
1095 * @param array $activity
1096 * @param string $actor
1098 * @return int user id
1100 private static function getBestUserForActivity(array $activity, string $actor): int
1103 $actor = $actor ?: JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
1105 $receivers = self::getReceivers($activity, $actor, [], false, false);
1106 foreach ($receivers as $receiver) {
1107 if ($receiver['type'] == self::TARGET_GLOBAL) {
1110 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
1111 $uid = $receiver['uid'];
1115 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
1117 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
1118 if (!empty($contact['uid'])) {
1119 $uid = $contact['uid'];
1126 // @TODO Missing documentation
1127 public static function getReceiverURL(array $activity): array
1131 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience', 'as:attributedTo'] as $element) {
1132 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1133 if (empty($receiver_list)) {
1137 foreach ($receiver_list as $receiver) {
1138 if ($receiver == 'Public') {
1139 Logger::warning('Not compacted public collection found', ['activity' => $activity]);
1140 $receiver = ActivityPub::PUBLIC_COLLECTION;
1142 if ($receiver == self::PUBLIC_COLLECTION) {
1143 $receiver = ActivityPub::PUBLIC_COLLECTION;
1145 $urls[$element][] = $receiver;
1153 * Fetch the receiver list from an activity array
1155 * @param array $activity
1156 * @param string $actor
1157 * @param array $tags
1158 * @param bool $fetch_unlisted
1161 * @return array with receivers (user id)
1162 * @throws \Exception
1164 private static function getReceivers(array $activity, string $actor, array $tags, bool $fetch_unlisted, bool $push): array
1166 $reply = $receivers = $profile = [];
1168 // When it is an answer, we inherit the receivers from the parent
1169 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
1170 if (!empty($replyto)) {
1171 $reply = [$replyto];
1173 // Fix possibly wrong item URI (could be an answer to a plink uri)
1174 $fixedReplyTo = Item::getURIByLink($replyto);
1175 if (!empty($fixedReplyTo)) {
1176 $reply[] = $fixedReplyTo;
1180 // Fetch all posts that refer to the object id
1181 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
1182 if (!empty($object_id)) {
1183 $reply[] = $object_id;
1186 if (!empty($actor)) {
1187 $profile = APContact::getByURL($actor);
1188 $followers = $profile['followers'] ?? '';
1189 $isGroup = ($profile['type'] ?? '') == 'Group';
1191 Contact::updateByUrlIfNeeded($actor);
1193 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1195 Logger::info('Empty actor', ['activity' => $activity]);
1200 $parent_followers = '';
1201 $parent = Post::selectFirstPost(['parent-author-link'], ['uri' => $reply]);
1202 if (!empty($parent['parent-author-link'])) {
1203 $parent_profile = APContact::getByURL($parent['parent-author-link']);
1204 if (!in_array($parent_profile['followers'] ?? '', ['', $followers])) {
1205 $parent_followers = $parent_profile['followers'];
1209 // We have to prevent false follower assumptions upon thread completions
1210 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1212 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience'] as $element) {
1213 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1214 if (empty($receiver_list)) {
1218 foreach ($receiver_list as $receiver) {
1219 if ($receiver == self::PUBLIC_COLLECTION) {
1220 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1223 // Add receiver "-1" for unlisted posts
1224 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1225 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1228 // Fetch the receivers for the public and the followers collection
1229 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$isGroup) || ($isGroup && ($element == 'as:audience'))) && !empty($actor)) {
1230 $receivers = self::getReceiverForActor($tags, $receivers, $follower_target, $profile);
1234 if ($receiver == $parent_followers) {
1235 $receivers = self::getReceiverForActor([], $receivers, $follower_target, $parent_profile);
1239 // Fetching all directly addressed receivers
1240 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1241 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1242 if (!DBA::isResult($contact)) {
1246 // Check if the potential receiver is following the actor
1247 // Exception: The receiver is targetted via "to" or this is a comment
1248 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1249 $networks = Protocol::FEDERATED;
1250 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1251 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1253 // Group posts are only accepted from group contacts
1254 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1255 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1258 if (!DBA::exists('contact', $condition)) {
1263 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1264 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1267 $type = self::TARGET_TO;
1270 $type = self::TARGET_CC;
1273 $type = self::TARGET_BTO;
1276 $type = self::TARGET_BCC;
1279 $type = self::TARGET_AUDIENCE;
1283 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1288 if (!empty($reply) && (!empty($receivers[0]) || !empty($receivers[-1]))) {
1289 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1290 while ($parent = Post::fetch($parents)) {
1291 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1293 DBA::close($parents);
1296 self::switchContacts($receivers, $actor);
1298 // "birdsitelive" is a service that mirrors tweets into the fediverse
1299 // These posts can be fetched without authentication, but are not marked as public
1300 // We treat them as unlisted posts to be able to handle them.
1301 // We always process deletion activities.
1302 $activity_type = JsonLD::fetchElement($activity, '@type');
1303 if (empty($receivers) && $fetch_unlisted && Contact::isPlatform($actor, 'birdsitelive')) {
1304 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1305 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1306 Logger::notice('Post from "birdsitelive" is set to "unlisted"', ['id' => JsonLD::fetchElement($activity, '@id')]);
1307 } elseif (empty($receivers) && in_array($activity_type, ['as:Delete', 'as:Undo'])) {
1308 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1309 } elseif (empty($receivers)) {
1310 Logger::notice('Post has got no receivers', ['fetch_unlisted' => $fetch_unlisted, 'actor' => $actor, 'id' => JsonLD::fetchElement($activity, '@id'), 'type' => $activity_type]);
1317 * Fetch the receiver list of a given actor
1319 * @param array $tags
1320 * @param array $receivers
1321 * @param integer $target_type
1322 * @param array $profile
1324 * @return array with receivers (user id)
1325 * @throws \Exception
1327 private static function getReceiverForActor(array $tags, array $receivers, int $target_type, array $profile): array
1329 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1330 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1332 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1333 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1334 while ($contact = DBA::fetch($contacts)) {
1335 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1336 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1339 DBA::close($contacts);
1345 * Tests if the contact is a valid receiver for this actor
1347 * @param array $contact
1348 * @param array $tags
1350 * @return bool with receivers (user id)
1351 * @throws \Exception
1353 private static function isValidReceiverForActor(array $contact, array $tags): bool
1355 // Are we following the contact? Then this is a valid receiver
1356 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1360 // When the possible receiver isn't a community, then it is no valid receiver
1361 $owner = User::getOwnerDataById($contact['uid']);
1362 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1366 // Is the community account tagged?
1367 foreach ($tags as $tag) {
1368 if ($tag['type'] != 'Mention') {
1372 if (Strings::compareLink($tag['href'], $owner['url'])) {
1381 * Switches existing contacts to ActivityPub
1383 * @param integer $cid Contact ID
1384 * @param integer $uid User ID
1385 * @param string $url Profile URL
1387 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1388 * @throws \ImagickException
1390 public static function switchContact(int $cid, int $uid, string $url)
1392 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1393 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1397 if (Contact::updateFromProbe($cid)) {
1398 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1401 // Send a new follow request to be sure that the connection still exists
1402 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1403 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1404 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1409 * @TODO Fix documentation and type-hints
1414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1415 * @throws \ImagickException
1417 private static function switchContacts($receivers, $actor)
1419 if (empty($actor)) {
1423 foreach ($receivers as $receiver) {
1424 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1425 if (DBA::isResult($contact)) {
1426 self::switchContact($contact['id'], $receiver['uid'], $actor);
1429 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1430 if (DBA::isResult($contact)) {
1431 self::switchContact($contact['id'], $receiver['uid'], $actor);
1437 * @TODO Fix documentation and type-hints
1439 * @param $object_data
1440 * @param array $activity
1444 private static function addActivityFields($object_data, array $activity)
1446 if (!empty($activity['published']) && empty($object_data['published'])) {
1447 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1450 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1451 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1454 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1455 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1457 if (!empty($object_data['object_id'])) {
1458 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1459 $objectId = Item::getURIByLink($object_data['object_id']);
1460 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1461 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1462 $object_data['object_id'] = $objectId;
1466 return $object_data;
1470 * Fetches the object data from external resources if needed
1472 * @param string $object_id Object ID of the provided object
1473 * @param array $object The provided object array
1474 * @param boolean $trust_source Do we trust the provided object?
1475 * @param integer $uid User ID for the signature that we use to fetch data
1477 * @return array|false with trusted and valid object data
1478 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1479 * @throws \ImagickException
1481 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1483 // By fetching the type we check if the object is complete.
1484 $type = JsonLD::fetchElement($object, '@type');
1486 if (!$trust_source || empty($type)) {
1487 $data = Processor::fetchCachedActivity($object_id, $uid);
1488 if (!empty($data)) {
1489 $object = JsonLD::compact($data);
1490 Logger::info('Fetched content for ' . $object_id);
1492 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1494 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1495 if (!DBA::isResult($item)) {
1496 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1499 Logger::info('Using already stored item for url ' . $object_id);
1500 $data = ActivityPub\Transmitter::createNote($item);
1501 $object = JsonLD::compact($data);
1504 $id = JsonLD::fetchElement($object, '@id');
1506 Logger::info('Empty id');
1510 if ($id != $object_id) {
1511 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1515 Logger::info('Using original object for url ' . $object_id);
1518 $type = JsonLD::fetchElement($object, '@type');
1520 Logger::info('Empty type');
1524 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1525 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1526 $object_data = self::processObject($object, '');
1528 if (!empty($data)) {
1529 $object_data['raw-object'] = json_encode($data);
1531 return $object_data;
1534 Logger::info('Unhandled object type: ' . $type);
1539 * Converts the language element (Used by Peertube)
1541 * @param array $languages
1542 * @return array Languages
1544 public static function processLanguages(array $languages): array
1546 if (empty($languages)) {
1550 $language_list = [];
1552 foreach ($languages as $language) {
1553 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1554 $language_list[$language['_:identifier']] = $language['as:name'];
1557 return $language_list;
1561 * Convert tags from JSON-LD format into a simplified format
1563 * @param array $tags Tags in JSON-LD format
1565 * @return array with tags in a simplified format
1567 public static function processTags(array $tags): array
1571 foreach ($tags as $tag) {
1577 'type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type') ?? ''),
1578 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1579 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')
1582 if (empty($element['type'])) {
1586 if (empty($element['href'])) {
1587 $element['href'] = $element['name'];
1590 $taglist[] = $element;
1596 * Convert emojis from JSON-LD format into a simplified format
1598 * @param array $emojis
1599 * @return array with emojis in a simplified format
1601 private static function processEmojis(array $emojis): array
1605 foreach ($emojis as $emoji) {
1606 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1610 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1612 'name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1616 $emojilist[] = $element;
1623 * Convert attachments from JSON-LD format into a simplified format
1625 * @param array $attachments Attachments in JSON-LD format
1627 * @return array Attachments in a simplified format
1629 private static function processAttachments(array $attachments): array
1633 // Removes empty values
1634 $attachments = array_filter($attachments);
1636 foreach ($attachments as $attachment) {
1637 switch (JsonLD::fetchElement($attachment, '@type')) {
1642 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1643 foreach ($urls as $url) {
1644 // Single scalar URL case
1645 if (is_string($url)) {
1650 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1651 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1652 if (Strings::startsWith($mediaType, 'image')) {
1661 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1662 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1664 'image' => $pageImage,
1668 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1669 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1670 $imagePreviewUrl = null;
1672 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1673 $imageVariants = [];
1674 $previewVariants = [];
1675 foreach ($urls as $url) {
1676 // Scalar URL, no discrimination possible
1677 if (is_string($url)) {
1678 $imageFullUrl = $url;
1682 // Not sure what to do with a different Link media type than the base Image, we skip
1683 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1687 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1689 // Default URL choice if no discriminating width is provided
1690 $imageFullUrl = $href ?? $imageFullUrl;
1692 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1694 if ($href && $width) {
1695 $imageVariants[$width] = $href;
1696 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1697 $previewVariants[abs(632 - $width)] = $href;
1701 if ($imageVariants) {
1702 // Taking the maximum size image
1703 ksort($imageVariants);
1704 $imageFullUrl = array_pop($imageVariants);
1706 // Taking the minimum number distance to the target distance
1707 ksort($previewVariants);
1708 $imagePreviewUrl = array_shift($previewVariants);
1711 unset($imageVariants);
1712 unset($previewVariants);
1716 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1717 'mediaType' => $mediaType,
1718 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1719 'url' => $imageFullUrl,
1720 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1725 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1726 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1727 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1728 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id') ?? JsonLD::fetchElement($attachment, 'as:href', '@id'),
1729 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1730 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1731 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1740 * Convert questions from JSON-LD format into a simplified format
1742 * @param array $object
1744 * @return array Questions in a simplified format
1746 private static function processQuestion(array $object): array
1750 if (!empty($object['as:oneOf'])) {
1751 $question['multiple'] = false;
1752 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1753 } elseif (!empty($object['as:anyOf'])) {
1754 $question['multiple'] = true;
1755 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1760 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1761 if (!empty($closed)) {
1762 $question['end-time'] = $closed;
1764 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1767 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1768 $question['options'] = [];
1772 foreach ($options as $option) {
1773 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1777 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1779 if (empty($option['as:replies'])) {
1783 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1785 $question['options'][] = ['name' => $name, 'replies' => $replies];
1787 $voters += (int)$replies;
1790 // For single choice question we can count the number of voters if not provided (like with Misskey)
1791 if (empty($question['voters']) && !$question['multiple']) {
1792 $question['voters'] = $voters;
1799 * Fetch the original source or content with the "language" Markdown or HTML
1801 * @param array $object
1802 * @param array $object_data
1804 * @return array Object data (?)
1805 * @throws \Exception
1807 private static function getSource(array $object, array $object_data): array
1809 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1810 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1811 if (!empty($object_data['source'])) {
1812 return $object_data;
1815 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1816 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1817 if (!empty($object_data['source'])) {
1818 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1819 return $object_data;
1822 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1823 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1824 if (!empty($object_data['source'])) {
1825 $object_data['source'] = HTML::toBBCode($object_data['source']);
1826 return $object_data;
1829 return $object_data;
1833 * Extracts a potential alternate URL from a list of additional URL elements
1835 * @param array $urls
1838 private static function extractAlternateUrl(array $urls): string
1841 foreach ($urls as $key => $url) {
1842 // Not a list but a single URL element
1843 if (!is_numeric($key)) {
1847 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1851 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1856 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1857 if (empty($mediatype)) {
1861 if ($mediatype == 'text/html') {
1862 $alternateUrl = $href;
1866 return $alternateUrl;
1870 * Check if the "as:url" element is an array with multiple links
1871 * This is the case with audio and video posts.
1872 * Then the links are added as attachments
1874 * @param array $urls The object URL list
1875 * @return array an array of attachments
1877 private static function processAttachmentUrls(array $urls): array
1880 foreach ($urls as $key => $url) {
1881 // Not a list but a single URL element
1882 if (!is_numeric($key)) {
1886 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1890 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1895 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1896 if (empty($mediatype)) {
1900 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1902 if ($filetype == 'audio') {
1903 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1904 } elseif ($filetype == 'video') {
1905 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1906 // PeerTube audio-only track
1907 if ($height === 0) {
1911 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1912 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1913 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1914 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1916 // For Torrent links we always store the highest resolution
1917 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1921 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1922 } elseif ($mediatype == 'application/x-mpegURL') {
1923 // PeerTube exception, actual video link is in the tags of this URL element
1924 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1928 return array_values($attachments);
1932 * Fetches data from the object part of an activity
1934 * @param array $object
1935 * @param string $actor
1937 * @return array|bool Object data or FALSE if $object does not contain @id element
1938 * @throws \Exception
1940 private static function processObject(array $object, string $actor)
1942 if (!JsonLD::fetchElement($object, '@id')) {
1946 $object_data = self::getObjectDataFromActivity($object);
1948 $receiverdata = self::getReceivers($object, $actor ?: $object_data['actor'] ?? '', $object_data['tags'], true, false);
1949 $receivers = $reception_types = [];
1950 foreach ($receiverdata as $key => $data) {
1951 $receivers[$key] = $data['uid'];
1952 $reception_types[$data['uid']] = $data['type'] ?? 0;
1955 $object_data['receiver_urls'] = self::getReceiverURL($object);
1956 $object_data['receiver'] = $receivers;
1957 $object_data['reception_type'] = $reception_types;
1959 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1960 unset($object_data['receiver'][-1]);
1961 unset($object_data['reception_type'][-1]);
1963 return $object_data;
1967 * Create an object data array from a given activity
1969 * @param array $object
1971 * @return array Object data
1973 public static function getObjectDataFromActivity(array $object): array
1976 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1977 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1978 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1980 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1981 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1982 $object_data['reply-to-id'] = $object_data['id'];
1984 // On activities the "reply to" is the id of the object it refers to
1985 if (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce']))) {
1986 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1987 if (!empty($object_id)) {
1988 $object_data['reply-to-id'] = $object_id;
1992 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1993 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1994 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1995 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1996 $object_data['reply-to-id'] = $replyToId;
2000 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
2001 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
2003 if (empty($object_data['updated'])) {
2004 $object_data['updated'] = $object_data['published'];
2007 if (empty($object_data['published']) && !empty($object_data['updated'])) {
2008 $object_data['published'] = $object_data['updated'];
2011 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
2012 if (empty($actor)) {
2013 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
2016 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
2017 $location = JsonLD::fetchElement($location, 'location', '@value');
2019 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
2020 // down to HTML and then finally format to plaintext.
2021 $location = Markdown::convert($location);
2022 $location = BBCode::toPlaintext($location);
2025 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
2026 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
2027 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
2028 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
2029 $object_data['actor'] = $object_data['author'] = $actor;
2030 $element = JsonLD::fetchElement($object, 'as:context', '@id');
2031 $object_data['context'] = $element != './' ? $element : null;
2032 $element = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
2033 $object_data['conversation'] = $element != './' ? $element : null;
2034 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
2035 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
2036 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
2037 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
2038 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
2039 $object_data = self::getSource($object, $object_data);
2040 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
2041 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
2042 $object_data['location'] = $location;
2043 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
2044 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
2045 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
2046 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
2047 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
2048 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
2049 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
2050 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
2051 $object_data['transmitted-languages'] = Processor::getPostLanguages($object);
2052 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
2053 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
2054 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
2056 // Special treatment for Hubzilla links
2057 if (is_array($object_data['alternate-url'])) {
2058 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
2060 if (!is_string($object_data['alternate-url'])) {
2061 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
2065 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
2066 $object_data['alternate-url'] = null;
2069 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
2070 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
2071 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
2074 // Support for quoted posts (Pleroma, Fedibird and Misskey)
2075 $object_data['quote-url'] = JsonLD::fetchElement($object, 'as:quoteUrl', '@value');
2076 if (empty($object_data['quote-url'])) {
2077 $object_data['quote-url'] = JsonLD::fetchElement($object, 'fedibird:quoteUri', '@value');
2079 if (empty($object_data['quote-url'])) {
2080 $object_data['quote-url'] = JsonLD::fetchElement($object, 'misskey:_misskey_quote', '@value');
2083 // Misskey adds some data to the standard "content" value for quoted posts for backwards compatibility.
2084 // Their own "_misskey_content" value does then contain the content without this extra data.
2085 if (!empty($object_data['quote-url'])) {
2086 $misskey_content = JsonLD::fetchElement($object, 'misskey:_misskey_content', '@value');
2087 if (!empty($misskey_content)) {
2088 $object_data['content'] = $misskey_content;
2092 // For page types we expect that the alternate url posts to some page.
2093 // So we add this to the attachments if it differs from the id.
2094 // Currently only Lemmy is using the page type.
2095 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
2096 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
2097 $object_data['alternate-url'] = null;
2100 if ($object_data['object_type'] == 'as:Question') {
2101 $object_data['question'] = self::processQuestion($object);
2104 return $object_data;
2108 * Add an object id to the list of arrived activities
2114 private static function addArrivedId(string $id)
2116 DBA::delete('arrived-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
2117 DBA::insert('arrived-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE);
2121 * Checks if the given object already arrived before
2127 private static function hasArrived(string $id): bool
2129 return DBA::exists('arrived-activity', ['object-id' => $id]);