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)) {
112 self::processRelayPost($ldactivity, $actor);
115 APContact::unmarkForArchival($apcontact);
118 $sig_contact = HTTPSignature::getKeyIdContact($header);
119 if (APContact::isRelay($sig_contact)) {
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 * Process incoming posts from relays
175 * @param array $activity
176 * @param string $actor
179 private static function processRelayPost(array $activity, string $actor)
181 $type = JsonLD::fetchElement($activity, '@type');
183 Logger::notice('Empty type', ['activity' => $activity, 'actor' => $actor]);
187 $object_type = JsonLD::fetchElement($activity, 'as:object', '@type') ?? '';
189 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
190 if (empty($object_id)) {
191 Logger::notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]);
195 $handle = ($type == 'as:Announce');
197 if (!$handle && in_array($type, ['as:Create', 'as:Update'])) {
198 $handle = in_array($object_type, self::CONTENT_TYPES);
202 $trust_source = false;
203 $object_data = self::prepareObjectData($activity, 0, false, $trust_source);
205 if (!$trust_source) {
206 Logger::notice('Activity trust could not be achieved.', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
210 if (empty($object_data)) {
211 Logger::notice('No object data found', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
215 if (self::routeActivities($object_data, $type, true)) {
216 Logger::debug('Handled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]);
218 Logger::info('Unhandled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, '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('Got relayed message id', ['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 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
244 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
250 * Fetches the object type for a given object id
252 * @param array $activity
253 * @param string $object_id Object ID of the provided object
254 * @param integer $uid User ID
256 * @return string with object type or NULL
257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
258 * @throws \ImagickException
260 public static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
262 if (!empty($activity['as:object'])) {
263 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
264 if (!empty($object_type)) {
269 if (Post::exists(['uri' => $object_id, 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]])) {
270 // We just assume "note" since it doesn't make a difference for the further processing
274 $profile = APContact::getByURL($object_id);
275 if (!empty($profile['type'])) {
276 APContact::unmarkForArchival($profile);
277 return 'as:' . $profile['type'];
280 $data = Processor::fetchCachedActivity($object_id, $uid);
282 $object = JsonLD::compact($data);
283 $type = JsonLD::fetchElement($object, '@type');
293 * Prepare the object array
295 * @param array $activity Array with activity data
296 * @param integer $uid User ID
297 * @param boolean $push Message had been pushed to our system
298 * @param boolean $trust_source Do we trust the source?
299 * @param string $original_actor Actor of the original activity. Used for receiver detection. (Optional)
301 * @return array with object data
302 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
303 * @throws \ImagickException
305 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source, string $original_actor = ''): array
307 $id = JsonLD::fetchElement($activity, '@id');
308 $type = JsonLD::fetchElement($activity, '@type');
309 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
311 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
312 $fetch_id = $object_id;
317 if (!empty($activity['as:object'])) {
318 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
323 if (!empty($id) && !$trust_source) {
324 $fetch_uid = $uid ?: self::getBestUserForActivity($activity, $original_actor);
326 $fetched_activity = Processor::fetchCachedActivity($fetch_id, $fetch_uid);
327 if (!empty($fetched_activity)) {
329 $object = JsonLD::compact($fetched_activity);
331 $fetched_id = JsonLD::fetchElement($object, '@id');
332 $fetched_type = JsonLD::fetchElement($object, '@type');
334 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
335 Logger::info('Activity had been fetched successfully', ['id' => $id]);
336 $trust_source = true;
338 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
339 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
340 $trust_source = true;
341 unset($object['@context']);
342 $activity['as:object'] = $object;
344 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
347 Logger::info('Activity could not been fetched', ['id' => $id]);
351 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
353 Logger::info('Empty actor', ['activity' => $activity]);
357 $type = JsonLD::fetchElement($activity, '@type');
359 // Fetch all receivers from to, cc, bto and bcc
360 $receiverdata = self::getReceivers($activity, $original_actor ?: $actor, [], false, $push || $fetched);
361 $receivers = $reception_types = [];
362 foreach ($receiverdata as $key => $data) {
363 $receivers[$key] = $data['uid'];
364 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
367 $urls = self::getReceiverURL($activity);
369 // When it is a delivery to a personal inbox we add that user to the receivers
371 $additional = [$uid => $uid];
372 $receivers = array_replace($receivers, $additional);
373 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]))) {
374 $reception_types[$uid] = self::TARGET_BCC;
375 $owner = User::getOwnerDataById($uid);
376 if (!empty($owner['url'])) {
377 $urls['as:bcc'][] = $owner['url'];
382 // We possibly need some user to fetch private content,
383 // so we fetch one out of the receivers if no uid is provided.
384 $fetch_uid = $uid ?: self::getBestUserForActivity($activity, $original_actor);
386 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
387 if (empty($object_id)) {
388 Logger::info('No object found');
392 if (!is_string($object_id)) {
393 Logger::info('Invalid object id', ['object' => $object_id]);
397 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
399 // Any activities on account types must not be altered
400 if (in_array($type, ['as:Flag'])) {
402 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
403 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
404 $object_data['object_ids'] = JsonLD::fetchElementArray($activity, 'as:object', '@id');
405 $object_data['content'] = JsonLD::fetchElement($activity, 'as:content', '@type');
406 } elseif (in_array($object_type, self::ACCOUNT_TYPES)) {
408 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
409 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
410 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
411 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
412 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
413 if (!$trust_source && ($type == 'as:Delete')) {
414 $apcontact = APContact::getByURL($object_data['object_id'], true);
415 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
417 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Invite']) || strpos($type, '#emojiReaction')) {
418 // Fetch the content only on activities where this matters
419 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
420 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $fetch_uid);
421 if (empty($object_data)) {
422 Logger::info("Object data couldn't be processed");
426 $object_data['object_id'] = $object_id;
428 // Test if it is an answer to a mail
429 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
430 $object_data['directmessage'] = true;
432 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
434 if (!empty(JsonLD::fetchElement($activity['as:object'], 'misskey:_misskey_talk'))) {
435 $object_data = self::setChatData($object_data, $receivers);
438 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
439 // Create a mostly empty array out of the activity data (instead of the object).
440 // This way we later don't have to check for the existence of each individual array element.
441 $object_data = self::processObject($activity, $original_actor);
442 $object_data['name'] = $type;
443 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
444 $object_data['object_id'] = $object_id;
445 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
446 } elseif (in_array($type, ['as:Add', 'as:Remove', 'as:Move'])) {
448 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
449 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
450 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
451 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
452 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
455 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
456 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
457 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
458 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
459 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
461 // An Undo is done on the object of an object, so we need that type as well
462 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
463 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
466 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
467 $trust_source = Processor::isActivityGone($object_data['object_id']);
468 if (!$trust_source) {
469 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
474 $object_data['push'] = $push;
476 $object_data = self::addActivityFields($object_data, $activity);
478 if (empty($object_data['object_type'])) {
479 $object_data['object_type'] = $object_type;
482 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience', 'as:attributedTo'] as $element) {
483 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
484 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
488 $object_data['type'] = $type;
489 $object_data['actor'] = $actor;
490 $object_data['item_receiver'] = $receivers;
491 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
492 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
494 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
495 // $author = $object_data['author'] ?? $actor;
496 // if (!empty($author) && !empty($object_data['id'])) {
497 // $author_host = parse_url($author, PHP_URL_HOST);
498 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
499 // if ($author_host == $id_host) {
500 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
502 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
503 // $trust_source = false;
507 $account = Contact::selectFirstAccount(['platform'], ['nurl' => Strings::normaliseLink($actor)]);
508 $platform = $account['platform'] ?? '';
510 Logger::info('Processing', ['type' => $object_data['type'], 'object_type' => $object_data['object_type'], 'id' => $object_data['id'], 'actor' => $actor, 'platform' => $platform]);
515 private static function setChatData(array $object_data, array $receivers): array
517 if (count($receivers) != 1) {
521 $user = User::getById(array_key_first($receivers), ['language']);
522 $l10n = DI::l10n()->withLang($user['language']);
523 $object_data['name'] = $l10n->t('Chat');
525 $mail = DBA::selectFirst('mail', ['uri'], ['uid' => array_key_first($receivers), 'title' => $object_data['name']], ['order' => ['id' => true]]);
526 if (!empty($mail['uri'])) {
527 $object_data['reply-to-id'] = $mail['uri'];
530 $object_data['directmessage'] = true;
531 Logger::debug('Got Misskey Chat');
536 * Fetches the first user id from the receiver array
538 * @param array $receivers Array with receivers
539 * @return integer user id;
541 public static function getFirstUserFromReceivers(array $receivers): int
543 foreach ($receivers as $receiver) {
544 if (!empty($receiver)) {
552 * Processes the activity object
554 * @param array $activity Array with activity data
555 * @param string $body The unprocessed body
556 * @param int|null $uid User ID
557 * @param boolean $trust_source Do we trust the source?
558 * @param boolean $push Message had been pushed to our system
559 * @param array $signer The signer of the post
563 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
564 * @throws \ImagickException
566 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
568 $type = JsonLD::fetchElement($activity, '@type');
570 Logger::info('Empty type', ['activity' => $activity]);
574 if (!DI::config()->get('system', 'process_view') && ($type == 'as:View')) {
575 Logger::info('View activities are ignored.', ['signer' => $signer, 'http_signer' => $http_signer]);
579 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
580 Logger::info('Empty object', ['activity' => $activity]);
584 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
586 Logger::info('Empty actor', ['activity' => $activity]);
590 if (is_array($activity['as:object'])) {
591 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
596 // Test the provided signatures against the actor and "attributedTo"
598 if (!empty($attributed_to) && !empty($actor)) {
599 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
601 $trust_source = in_array($actor, $signer);
605 // Lemmy announces activities.
606 // To simplify the further processing, we modify the received object.
607 // For announced "create" activities we remove the middle layer.
608 // For the rest (like, dislike, update, ...) we just process the activity directly.
609 $original_actor = '';
610 $object_type = JsonLD::fetchElement($activity['as:object'] ?? [], '@type');
611 if (($type == 'as:Announce') && !empty($object_type) && !in_array($object_type, self::CONTENT_TYPES) && self::isGroup($actor)) {
612 $object_object_type = JsonLD::fetchElement($activity['as:object']['as:object'] ?? [], '@type');
613 if (in_array($object_type, ['as:Create']) && in_array($object_object_type, self::CONTENT_TYPES)) {
614 Logger::debug('Replace "create" activity with inner object', ['type' => $object_type, 'object_type' => $object_object_type]);
615 $activity['as:object'] = $activity['as:object']['as:object'];
616 } elseif (in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
617 Logger::debug('Change announced activity to activity', ['type' => $object_type]);
618 $original_actor = $actor;
619 $type = $object_type;
620 $activity = $activity['as:object'];
622 Logger::info('Unhandled announced activity', ['type' => $object_type, 'object_type' => $object_object_type]);
626 // $trust_source is called by reference and is set to true if the content was retrieved successfully
627 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source, $original_actor);
628 if (empty($object_data)) {
629 Logger::info('No object data found', ['activity' => $activity]);
633 if (!empty($body) && empty($object_data['raw'])) {
634 $object_data['raw'] = $body;
637 // Internal flag for thread completion. See Processor.php
638 if (!empty($activity['thread-completion'])) {
639 $object_data['thread-completion'] = $activity['thread-completion'];
642 if (!empty($activity['completion-mode'])) {
643 $object_data['completion-mode'] = $activity['completion-mode'];
646 if (!empty($activity['thread-children-type'])) {
647 $object_data['thread-children-type'] = $activity['thread-children-type'];
650 // Internal flag for posts that arrived via relay
651 if (!empty($activity['from-relay'])) {
652 $object_data['from-relay'] = $activity['from-relay'];
655 if ($type == 'as:Announce') {
656 $object_data['object_activity'] = $activity;
659 if (($type == 'as:Create') && $trust_source && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE])) {
660 if (self::hasArrived($object_data['object_id'])) {
661 Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]);
664 self::addArrivedId($object_data['object_id']);
666 if (Queue::exists($object_data['object_id'], $type)) {
667 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
670 } elseif (($type == 'as:Create') && $trust_source && !self::hasArrived($object_data['object_id'])) {
671 self::addArrivedId($object_data['object_id']);
674 $decouple = DI::config()->get('system', 'decoupled_receiver') && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE]);
676 if ($decouple && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
677 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
680 if (!$trust_source) {
681 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
685 if (!empty($object_data['entry-id']) && $decouple && ($push || in_array($completion, [self::COMPLETION_RELAY, self::COMPLETION_ASYNC]))) {
686 if (Queue::isProcessable($object_data['entry-id'])) {
687 // We delay by 5 seconds to allow to accumulate all receivers
688 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
689 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
690 $wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
691 Queue::setWorkerId($object_data['entry-id'], $wid);
693 Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]);
698 if (!empty($activity['recursion-depth'])) {
699 $object_data['recursion-depth'] = $activity['recursion-depth'];
702 if (!self::routeActivities($object_data, $type, $push, true, $uid)) {
703 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
704 Queue::remove($object_data);
710 * Checks if the provided actor is a group account
712 * @param string $actor
715 private static function isGroup(string $actor): bool
717 $profile = APContact::getByURL($actor);
718 return ($profile['type'] ?? '') == 'Group';
724 * @param array $object_data
725 * @param string $type
727 * @param bool $fetch_parents
730 * @return boolean Could the activity be routed?
732 public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true, int $uid = 0): bool
736 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
737 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
738 ActivityPub\Processor::postItem($object_data, $item);
739 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
740 // Unhandled Peertube activity
741 Queue::remove($object_data);
742 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
743 ActivityPub\Processor::updatePerson($object_data);
750 if (in_array($object_data['object_type'], ['as:Event'])) {
751 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
752 ActivityPub\Processor::postItem($object_data, $item);
759 if ($object_data['object_type'] == 'as:tag') {
760 ActivityPub\Processor::addTag($object_data);
761 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
762 ActivityPub\Processor::addToFeaturedCollection($object_data);
763 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
764 // We don't have the object here or it is deleted. We ignore this activity.
765 Queue::remove($object_data);
772 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
773 if (!Item::searchByLink($object_data['object_id'], $uid)) {
774 if (ActivityPub\Processor::fetchMissingActivity($object_data['object_id'], [], $object_data['actor'], self::COMPLETION_ANNOUNCE, $uid)) {
775 Logger::debug('Created announced id', ['uid' => $uid, 'id' => $object_data['object_id']]);
776 Queue::remove($object_data);
778 Logger::debug('Announced id was not created', ['uid' => $uid, 'id' => $object_data['object_id']]);
779 Queue::remove($object_data);
783 Logger::info('Announced id already exists', ['uid' => $uid, 'id' => $object_data['object_id']]);
784 Queue::remove($object_data);
787 ActivityPub\Processor::createActivity($object_data, Activity::ANNOUNCE);
788 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
789 // We don't have the object here or it is deleted. We ignore this activity.
790 Queue::remove($object_data);
797 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
798 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
799 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
800 // We don't have the object here or it is deleted. We ignore this activity.
801 Queue::remove($object_data);
808 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
809 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
810 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
811 // We don't have the object here or it is deleted. We ignore this activity.
812 Queue::remove($object_data);
818 case 'as:TentativeAccept':
819 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
820 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
827 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
828 ActivityPub\Processor::updateItem($object_data);
829 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
830 ActivityPub\Processor::updatePerson($object_data);
831 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
832 // Unhandled Peertube activity
833 Queue::remove($object_data);
840 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
841 ActivityPub\Processor::deleteItem($object_data);
842 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
843 ActivityPub\Processor::deletePerson($object_data);
844 } elseif ($object_data['object_type'] == '') {
845 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
846 Queue::remove($object_data);
853 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
854 ActivityPub\Processor::movePerson($object_data);
861 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
862 ActivityPub\Processor::blockAccount($object_data);
869 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
870 ActivityPub\Processor::ReportAccount($object_data);
877 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
878 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
879 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
880 // We don't have the object here or it is deleted. We ignore this activity.
881 Queue::remove($object_data);
888 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
889 ActivityPub\Processor::followUser($object_data);
890 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
891 $object_data['reply-to-id'] = $object_data['object_id'];
892 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
899 if ($object_data['object_type'] == 'as:Follow') {
900 if (!empty($object_data['object_actor'])) {
901 ActivityPub\Processor::acceptFollowUser($object_data);
903 Logger::notice('Unhandled "accept follow" message.', ['object_data' => $object_data]);
905 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
906 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
907 } elseif (!empty($object_data['object_id']) && empty($object_data['object_actor']) && empty($object_data['object_type'])) {
908 // Follow acceptances from gup.pe only contain the object id
909 ActivityPub\Processor::acceptFollowUser($object_data);
916 if ($object_data['object_type'] == 'as:Follow') {
917 ActivityPub\Processor::rejectFollowUser($object_data);
918 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
919 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
926 if (($object_data['object_type'] == 'as:Follow') &&
927 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
928 ActivityPub\Processor::undoFollowUser($object_data);
929 } elseif (($object_data['object_type'] == 'as:Follow') &&
930 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
931 ActivityPub\Processor::undoActivity($object_data);
932 } elseif (($object_data['object_type'] == 'as:Accept') &&
933 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
934 ActivityPub\Processor::rejectFollowUser($object_data);
935 } elseif (($object_data['object_type'] == 'as:Block') &&
936 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
937 ActivityPub\Processor::unblockAccount($object_data);
938 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
939 empty($object_data['object_object_type'])) {
940 // We cannot detect the target object. So we can ignore it.
941 Queue::remove($object_data);
942 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
943 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
944 ActivityPub\Processor::undoActivity($object_data);
945 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
946 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
947 // Unhandled Peertube activity
948 Queue::remove($object_data);
949 } elseif (in_array($object_data['object_type'], ['as:Delete'])) {
950 // We cannot undo deletions, so we just ignore this
951 Queue::remove($object_data);
952 } elseif (in_array($object_data['object_object_type'], ['as:Tombstone'])) {
953 // The object is a tombstone, we ignore any actions on it.
954 Queue::remove($object_data);
961 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
962 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
963 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
964 // We don't have the object here or it is deleted. We ignore this activity.
965 Queue::remove($object_data);
971 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
972 ActivityPub\Processor::createActivity($object_data, Activity::READ);
973 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
974 // We don't have the object here or it is deleted. We ignore this activity.
975 Queue::remove($object_data);
981 case 'litepub:EmojiReact':
982 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
983 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
984 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
985 // We don't have the object here or it is deleted. We ignore this activity.
986 Queue::remove($object_data);
993 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
1000 * Stores unhandled or unknown Activities as a file
1002 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
1003 * @param string $type Activity type
1004 * @param array $object_data Preprocessed array that is generated out of the received activity
1005 * @param array $activity Array with activity data
1006 * @param string $body The unprocessed body
1007 * @param integer $uid User ID
1008 * @param boolean $trust_source Do we trust the source?
1009 * @param boolean $push Message had been pushed to our system
1010 * @param array $signer The signer of the post
1013 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 = [])
1015 if (!DI::config()->get('debug', 'ap_log_unknown')) {
1019 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
1021 if (!empty($object_data['object_type'])) {
1022 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
1025 if (!empty($object_data['object_object_type'])) {
1026 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
1029 $tempfile = tempnam(System::getTempPath(), $file);
1030 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));
1031 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], 'object_object_type' => $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
1035 * Fetch a user id from an activity array
1037 * @param array $activity
1038 * @param string $actor
1040 * @return int user id
1042 public static function getBestUserForActivity(array $activity, string $actor = ''): int
1045 $actor = $actor ?: JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
1047 $receivers = self::getReceivers($activity, $actor, [], false, false);
1048 foreach ($receivers as $receiver) {
1049 if ($receiver['type'] == self::TARGET_GLOBAL) {
1052 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
1053 $uid = $receiver['uid'];
1057 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
1059 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
1060 if (!empty($contact['uid'])) {
1061 $uid = $contact['uid'];
1068 // @TODO Missing documentation
1069 public static function getReceiverURL(array $activity): array
1073 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience', 'as:attributedTo'] as $element) {
1074 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1075 if (empty($receiver_list)) {
1079 foreach ($receiver_list as $receiver) {
1080 if ($receiver == 'Public') {
1081 Logger::warning('Not compacted public collection found', ['activity' => $activity]);
1082 $receiver = ActivityPub::PUBLIC_COLLECTION;
1084 if ($receiver == self::PUBLIC_COLLECTION) {
1085 $receiver = ActivityPub::PUBLIC_COLLECTION;
1087 $urls[$element][] = $receiver;
1095 * Fetch the receiver list from an activity array
1097 * @param array $activity
1098 * @param string $actor
1099 * @param array $tags
1100 * @param bool $fetch_unlisted
1103 * @return array with receivers (user id)
1104 * @throws \Exception
1106 private static function getReceivers(array $activity, string $actor, array $tags, bool $fetch_unlisted, bool $push): array
1108 $reply = $receivers = $profile = [];
1110 // When it is an answer, we inherit the receivers from the parent
1111 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
1112 if (!empty($replyto)) {
1113 $reply = [$replyto];
1115 // Fix possibly wrong item URI (could be an answer to a plink uri)
1116 $fixedReplyTo = Item::getURIByLink($replyto);
1117 if (!empty($fixedReplyTo)) {
1118 $reply[] = $fixedReplyTo;
1122 // Fetch all posts that refer to the object id
1123 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
1124 if (!empty($object_id)) {
1125 $reply[] = $object_id;
1128 if (!empty($actor)) {
1129 $profile = APContact::getByURL($actor);
1130 $followers = $profile['followers'] ?? '';
1131 $isGroup = ($profile['type'] ?? '') == 'Group';
1133 Contact::updateByUrlIfNeeded($actor);
1135 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1137 Logger::info('Empty actor', ['activity' => $activity]);
1142 // We have to prevent false follower assumptions upon thread completions
1143 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1145 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc','as:audience'] as $element) {
1146 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1147 if (empty($receiver_list)) {
1151 foreach ($receiver_list as $receiver) {
1152 if ($receiver == self::PUBLIC_COLLECTION) {
1153 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1156 // Add receiver "-1" for unlisted posts
1157 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1158 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1161 // Fetch the receivers for the public and the followers collection
1162 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$isGroup) || ($isGroup && ($element == 'as:audience'))) && !empty($actor)) {
1163 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1167 // Fetching all directly addressed receivers
1168 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1169 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1170 if (!DBA::isResult($contact)) {
1174 // Check if the potential receiver is following the actor
1175 // Exception: The receiver is targetted via "to" or this is a comment
1176 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1177 $networks = Protocol::FEDERATED;
1178 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1179 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1181 // Group posts are only accepted from group contacts
1182 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1183 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1186 if (!DBA::exists('contact', $condition)) {
1191 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1192 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1195 $type = self::TARGET_TO;
1198 $type = self::TARGET_CC;
1201 $type = self::TARGET_BTO;
1204 $type = self::TARGET_BCC;
1207 $type = self::TARGET_AUDIENCE;
1211 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1216 if (!empty($reply) && (!empty($receivers[0]) || !empty($receivers[-1]))) {
1217 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1218 while ($parent = Post::fetch($parents)) {
1219 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1221 DBA::close($parents);
1224 self::switchContacts($receivers, $actor);
1226 // "birdsitelive" is a service that mirrors tweets into the fediverse
1227 // These posts can be fetched without authentication, but are not marked as public
1228 // We treat them as unlisted posts to be able to handle them.
1229 // We always process deletion activities.
1230 $activity_type = JsonLD::fetchElement($activity, '@type');
1231 if (empty($receivers) && $fetch_unlisted && Contact::isPlatform($actor, 'birdsitelive')) {
1232 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1233 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1234 Logger::notice('Post from "birdsitelive" is set to "unlisted"', ['id' => JsonLD::fetchElement($activity, '@id')]);
1235 } elseif (empty($receivers) && in_array($activity_type, ['as:Delete', 'as:Undo'])) {
1236 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1237 } elseif (empty($receivers)) {
1238 Logger::notice('Post has got no receivers', ['fetch_unlisted' => $fetch_unlisted, 'actor' => $actor, 'id' => JsonLD::fetchElement($activity, '@id'), 'type' => $activity_type]);
1245 * Fetch the receiver list of a given actor
1247 * @param string $actor
1248 * @param array $tags
1249 * @param array $receivers
1250 * @param integer $target_type
1251 * @param array $profile
1253 * @return array with receivers (user id)
1254 * @throws \Exception
1256 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1258 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1259 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1261 if (!empty($profile['uri-id'])) {
1262 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1263 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1264 while ($contact = DBA::fetch($contacts)) {
1265 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1266 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1269 DBA::close($contacts);
1271 // This part will only be called while post update 1426 wasn't finished
1272 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1273 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1274 while ($contact = DBA::fetch($contacts)) {
1275 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1276 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1279 DBA::close($contacts);
1281 // The queries are split because of performance issues
1282 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1283 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1284 while ($contact = DBA::fetch($contacts)) {
1285 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1286 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1289 DBA::close($contacts);
1295 * Tests if the contact is a valid receiver for this actor
1297 * @param array $contact
1298 * @param array $tags
1300 * @return bool with receivers (user id)
1301 * @throws \Exception
1303 private static function isValidReceiverForActor(array $contact, array $tags): bool
1305 // Are we following the contact? Then this is a valid receiver
1306 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1310 // When the possible receiver isn't a community, then it is no valid receiver
1311 $owner = User::getOwnerDataById($contact['uid']);
1312 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1316 // Is the community account tagged?
1317 foreach ($tags as $tag) {
1318 if ($tag['type'] != 'Mention') {
1322 if (Strings::compareLink($tag['href'], $owner['url'])) {
1331 * Switches existing contacts to ActivityPub
1333 * @param integer $cid Contact ID
1334 * @param integer $uid User ID
1335 * @param string $url Profile URL
1337 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1338 * @throws \ImagickException
1340 public static function switchContact(int $cid, int $uid, string $url)
1342 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1343 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1347 if (Contact::updateFromProbe($cid)) {
1348 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1351 // Send a new follow request to be sure that the connection still exists
1352 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1353 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1354 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1359 * @TODO Fix documentation and type-hints
1364 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1365 * @throws \ImagickException
1367 private static function switchContacts($receivers, $actor)
1369 if (empty($actor)) {
1373 foreach ($receivers as $receiver) {
1374 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1375 if (DBA::isResult($contact)) {
1376 self::switchContact($contact['id'], $receiver['uid'], $actor);
1379 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1380 if (DBA::isResult($contact)) {
1381 self::switchContact($contact['id'], $receiver['uid'], $actor);
1387 * @TODO Fix documentation and type-hints
1389 * @param $object_data
1390 * @param array $activity
1394 private static function addActivityFields($object_data, array $activity)
1396 if (!empty($activity['published']) && empty($object_data['published'])) {
1397 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1400 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1401 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1404 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1405 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1407 if (!empty($object_data['object_id'])) {
1408 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1409 $objectId = Item::getURIByLink($object_data['object_id']);
1410 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1411 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1412 $object_data['object_id'] = $objectId;
1416 return $object_data;
1420 * Fetches the object data from external resources if needed
1422 * @param string $object_id Object ID of the provided object
1423 * @param array $object The provided object array
1424 * @param boolean $trust_source Do we trust the provided object?
1425 * @param integer $uid User ID for the signature that we use to fetch data
1427 * @return array|false with trusted and valid object data
1428 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1429 * @throws \ImagickException
1431 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1433 // By fetching the type we check if the object is complete.
1434 $type = JsonLD::fetchElement($object, '@type');
1436 if (!$trust_source || empty($type)) {
1437 $data = Processor::fetchCachedActivity($object_id, $uid);
1438 if (!empty($data)) {
1439 $object = JsonLD::compact($data);
1440 Logger::info('Fetched content for ' . $object_id);
1442 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1444 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1445 if (!DBA::isResult($item)) {
1446 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1449 Logger::info('Using already stored item for url ' . $object_id);
1450 $data = ActivityPub\Transmitter::createNote($item);
1451 $object = JsonLD::compact($data);
1454 $id = JsonLD::fetchElement($object, '@id');
1456 Logger::info('Empty id');
1460 if ($id != $object_id) {
1461 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1465 Logger::info('Using original object for url ' . $object_id);
1468 $type = JsonLD::fetchElement($object, '@type');
1470 Logger::info('Empty type');
1474 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1475 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1476 $object_data = self::processObject($object, '');
1478 if (!empty($data)) {
1479 $object_data['raw-object'] = json_encode($data);
1481 return $object_data;
1484 Logger::info('Unhandled object type: ' . $type);
1489 * Converts the language element (Used by Peertube)
1491 * @param array $languages
1492 * @return array Languages
1494 public static function processLanguages(array $languages): array
1496 if (empty($languages)) {
1500 $language_list = [];
1502 foreach ($languages as $language) {
1503 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1504 $language_list[$language['_:identifier']] = $language['as:name'];
1507 return $language_list;
1511 * Convert tags from JSON-LD format into a simplified format
1513 * @param array $tags Tags in JSON-LD format
1515 * @return array with tags in a simplified format
1517 public static function processTags(array $tags): array
1521 foreach ($tags as $tag) {
1526 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type') ?? ''),
1527 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1528 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1530 if (empty($element['type'])) {
1534 if (empty($element['href'])) {
1535 $element['href'] = $element['name'];
1538 $taglist[] = $element;
1544 * Convert emojis from JSON-LD format into a simplified format
1546 * @param array $emojis
1547 * @return array with emojis in a simplified format
1549 private static function processEmojis(array $emojis): array
1553 foreach ($emojis as $emoji) {
1554 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1558 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1559 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1562 $emojilist[] = $element;
1569 * Convert attachments from JSON-LD format into a simplified format
1571 * @param array $attachments Attachments in JSON-LD format
1573 * @return array Attachments in a simplified format
1575 private static function processAttachments(array $attachments): array
1579 // Removes empty values
1580 $attachments = array_filter($attachments);
1582 foreach ($attachments as $attachment) {
1583 switch (JsonLD::fetchElement($attachment, '@type')) {
1588 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1589 foreach ($urls as $url) {
1590 // Single scalar URL case
1591 if (is_string($url)) {
1596 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1597 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1598 if (Strings::startsWith($mediaType, 'image')) {
1607 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1608 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1610 'image' => $pageImage,
1614 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1615 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1616 $imagePreviewUrl = null;
1618 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1619 $imageVariants = [];
1620 $previewVariants = [];
1621 foreach ($urls as $url) {
1622 // Scalar URL, no discrimination possible
1623 if (is_string($url)) {
1624 $imageFullUrl = $url;
1628 // Not sure what to do with a different Link media type than the base Image, we skip
1629 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1633 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1635 // Default URL choice if no discriminating width is provided
1636 $imageFullUrl = $href ?? $imageFullUrl;
1638 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1640 if ($href && $width) {
1641 $imageVariants[$width] = $href;
1642 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1643 $previewVariants[abs(632 - $width)] = $href;
1647 if ($imageVariants) {
1648 // Taking the maximum size image
1649 ksort($imageVariants);
1650 $imageFullUrl = array_pop($imageVariants);
1652 // Taking the minimum number distance to the target distance
1653 ksort($previewVariants);
1654 $imagePreviewUrl = array_shift($previewVariants);
1657 unset($imageVariants);
1658 unset($previewVariants);
1662 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1663 'mediaType' => $mediaType,
1664 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1665 'url' => $imageFullUrl,
1666 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1671 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1672 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1673 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1674 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id') ?? JsonLD::fetchElement($attachment, 'as:href', '@id'),
1675 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1676 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1677 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1686 * Convert questions from JSON-LD format into a simplified format
1688 * @param array $object
1690 * @return array Questions in a simplified format
1692 private static function processQuestion(array $object): array
1696 if (!empty($object['as:oneOf'])) {
1697 $question['multiple'] = false;
1698 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1699 } elseif (!empty($object['as:anyOf'])) {
1700 $question['multiple'] = true;
1701 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1706 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1707 if (!empty($closed)) {
1708 $question['end-time'] = $closed;
1710 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1713 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1714 $question['options'] = [];
1718 foreach ($options as $option) {
1719 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1723 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1725 if (empty($option['as:replies'])) {
1729 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1731 $question['options'][] = ['name' => $name, 'replies' => $replies];
1733 $voters += (int)$replies;
1736 // For single choice question we can count the number of voters if not provided (like with Misskey)
1737 if (empty($question['voters']) && !$question['multiple']) {
1738 $question['voters'] = $voters;
1745 * Fetch the original source or content with the "language" Markdown or HTML
1747 * @param array $object
1748 * @param array $object_data
1750 * @return array Object data (?)
1751 * @throws \Exception
1753 private static function getSource(array $object, array $object_data): array
1755 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1756 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1757 if (!empty($object_data['source'])) {
1758 return $object_data;
1761 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1762 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1763 if (!empty($object_data['source'])) {
1764 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1765 return $object_data;
1768 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1769 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1770 if (!empty($object_data['source'])) {
1771 $object_data['source'] = HTML::toBBCode($object_data['source']);
1772 return $object_data;
1775 return $object_data;
1779 * Extracts a potential alternate URL from a list of additional URL elements
1781 * @param array $urls
1784 private static function extractAlternateUrl(array $urls): string
1787 foreach ($urls as $key => $url) {
1788 // Not a list but a single URL element
1789 if (!is_numeric($key)) {
1793 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1797 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1802 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1803 if (empty($mediatype)) {
1807 if ($mediatype == 'text/html') {
1808 $alternateUrl = $href;
1812 return $alternateUrl;
1816 * Check if the "as:url" element is an array with multiple links
1817 * This is the case with audio and video posts.
1818 * Then the links are added as attachments
1820 * @param array $urls The object URL list
1821 * @return array an array of attachments
1823 private static function processAttachmentUrls(array $urls): array
1826 foreach ($urls as $key => $url) {
1827 // Not a list but a single URL element
1828 if (!is_numeric($key)) {
1832 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1836 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1841 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1842 if (empty($mediatype)) {
1846 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1848 if ($filetype == 'audio') {
1849 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1850 } elseif ($filetype == 'video') {
1851 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1852 // PeerTube audio-only track
1853 if ($height === 0) {
1857 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1858 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1859 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1860 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1862 // For Torrent links we always store the highest resolution
1863 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1867 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1868 } elseif ($mediatype == 'application/x-mpegURL') {
1869 // PeerTube exception, actual video link is in the tags of this URL element
1870 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1874 return array_values($attachments);
1878 * Fetches data from the object part of an activity
1880 * @param array $object
1881 * @param string $actor
1883 * @return array|bool Object data or FALSE if $object does not contain @id element
1884 * @throws \Exception
1886 private static function processObject(array $object, string $actor)
1888 if (!JsonLD::fetchElement($object, '@id')) {
1892 $object_data = self::getObjectDataFromActivity($object);
1894 $receiverdata = self::getReceivers($object, $actor ?: $object_data['actor'] ?? '', $object_data['tags'], true, false);
1895 $receivers = $reception_types = [];
1896 foreach ($receiverdata as $key => $data) {
1897 $receivers[$key] = $data['uid'];
1898 $reception_types[$data['uid']] = $data['type'] ?? 0;
1901 $object_data['receiver_urls'] = self::getReceiverURL($object);
1902 $object_data['receiver'] = $receivers;
1903 $object_data['reception_type'] = $reception_types;
1905 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1906 unset($object_data['receiver'][-1]);
1907 unset($object_data['reception_type'][-1]);
1909 return $object_data;
1913 * Create an object data array from a given activity
1915 * @param array $object
1917 * @return array Object data
1919 public static function getObjectDataFromActivity(array $object): array
1922 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1923 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1924 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1926 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1927 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1928 $object_data['reply-to-id'] = $object_data['id'];
1930 // On activities the "reply to" is the id of the object it refers to
1931 if (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce']))) {
1932 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1933 if (!empty($object_id)) {
1934 $object_data['reply-to-id'] = $object_id;
1938 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1939 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1940 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1941 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1942 $object_data['reply-to-id'] = $replyToId;
1946 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1947 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1949 if (empty($object_data['updated'])) {
1950 $object_data['updated'] = $object_data['published'];
1953 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1954 $object_data['published'] = $object_data['updated'];
1957 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1958 if (empty($actor)) {
1959 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1962 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1963 $location = JsonLD::fetchElement($location, 'location', '@value');
1965 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1966 // down to HTML and then finally format to plaintext.
1967 $location = Markdown::convert($location);
1968 $location = BBCode::toPlaintext($location);
1971 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1972 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1973 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1974 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1975 $object_data['actor'] = $object_data['author'] = $actor;
1976 $element = JsonLD::fetchElement($object, 'as:context', '@id');
1977 $object_data['context'] = $element != './' ? $element : null;
1978 $element = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1979 $object_data['conversation'] = $element != './' ? $element : null;
1980 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1981 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1982 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1983 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1984 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1985 $object_data = self::getSource($object, $object_data);
1986 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1987 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1988 $object_data['location'] = $location;
1989 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1990 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1991 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1992 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1993 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1994 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1995 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1996 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1997 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1998 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1999 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
2001 // Special treatment for Hubzilla links
2002 if (is_array($object_data['alternate-url'])) {
2003 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
2005 if (!is_string($object_data['alternate-url'])) {
2006 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
2010 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
2011 $object_data['alternate-url'] = null;
2014 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
2015 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
2016 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
2019 // Support for quoted posts (Pleroma, Fedibird and Misskey)
2020 $object_data['quote-url'] = JsonLD::fetchElement($object, 'as:quoteUrl', '@value');
2021 if (empty($object_data['quote-url'])) {
2022 $object_data['quote-url'] = JsonLD::fetchElement($object, 'fedibird:quoteUri', '@value');
2024 if (empty($object_data['quote-url'])) {
2025 $object_data['quote-url'] = JsonLD::fetchElement($object, 'misskey:_misskey_quote', '@value');
2028 // Misskey adds some data to the standard "content" value for quoted posts for backwards compatibility.
2029 // Their own "_misskey_content" value does then contain the content without this extra data.
2030 if (!empty($object_data['quote-url'])) {
2031 $misskey_content = JsonLD::fetchElement($object, 'misskey:_misskey_content', '@value');
2032 if (!empty($misskey_content)) {
2033 $object_data['content'] = $misskey_content;
2037 // For page types we expect that the alternate url posts to some page.
2038 // So we add this to the attachments if it differs from the id.
2039 // Currently only Lemmy is using the page type.
2040 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
2041 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
2042 $object_data['alternate-url'] = null;
2045 if ($object_data['object_type'] == 'as:Question') {
2046 $object_data['question'] = self::processQuestion($object);
2049 return $object_data;
2053 * Add an object id to the list of arrived activities
2059 private static function addArrivedId(string $id)
2061 DBA::delete('arrived-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
2062 DBA::insert('arrived-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE);
2066 * Checks if the given object already arrived before
2072 private static function hasArrived(string $id): bool
2074 return DBA::exists('arrived-activity', ['object-id' => $id]);