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;
85 * Checks incoming message from the inbox
87 * @param string $body Body string
88 * @param array $header Header lines
89 * @param integer $uid User ID
93 public static function processInbox(string $body, array $header, int $uid)
95 $activity = json_decode($body, true);
96 if (empty($activity)) {
97 Logger::warning('Invalid body.');
101 $ldactivity = JsonLD::compact($activity);
103 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
105 $apcontact = APContact::getByURL($actor);
107 if (empty($apcontact)) {
108 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
110 } elseif (APContact::isRelay($apcontact)) {
111 self::processRelayPost($ldactivity, $actor);
114 APContact::unmarkForArchival($apcontact);
117 $sig_contact = HTTPSignature::getKeyIdContact($header);
118 if (APContact::isRelay($sig_contact)) {
119 Logger::info('Message from a relay', ['url' => $sig_contact['url']]);
120 self::processRelayPost($ldactivity, $sig_contact['url']);
124 $http_signer = HTTPSignature::getSigner($body, $header);
125 if ($http_signer === false) {
126 Logger::notice('Invalid HTTP signature, message will not be trusted.', ['uid' => $uid, 'actor' => $actor, 'header' => $header, 'body' => $body]);
128 } elseif (empty($http_signer)) {
129 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
132 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
133 $signer = [$http_signer];
136 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
138 if ($http_signer === false) {
139 $trust_source = false;
140 } elseif (LDSignature::isSigned($activity)) {
141 $ld_signer = LDSignature::getSigner($activity);
142 if (empty($ld_signer)) {
143 Logger::info('Invalid JSON-LD signature from ' . $actor);
144 } elseif ($ld_signer != $http_signer) {
145 $signer[] = $ld_signer;
147 if (!empty($ld_signer && ($actor == $http_signer))) {
148 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
149 $trust_source = true;
150 } elseif (!empty($ld_signer)) {
151 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
152 $trust_source = true;
153 } elseif ($actor == $http_signer) {
154 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
155 $trust_source = true;
157 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
158 $trust_source = false;
160 } elseif ($actor == $http_signer) {
161 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
162 $trust_source = true;
164 Logger::info('No JSON-LD signature, different actor.');
165 $trust_source = false;
168 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
172 * Process incoming posts from relays
174 * @param array $activity
175 * @param string $actor
178 private static function processRelayPost(array $activity, string $actor)
180 $type = JsonLD::fetchElement($activity, '@type');
182 Logger::notice('Empty type', ['activity' => $activity, 'actor' => $actor]);
186 $object_type = JsonLD::fetchElement($activity, 'as:object', '@type') ?? '';
188 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
189 if (empty($object_id)) {
190 Logger::notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]);
194 $handle = ($type == 'as:Announce');
196 if (!$handle && in_array($type, ['as:Create', 'as:Update'])) {
197 $handle = in_array($object_type, self::CONTENT_TYPES);
201 $trust_source = false;
202 $object_data = self::prepareObjectData($activity, 0, false, $trust_source);
204 if (!$trust_source) {
205 Logger::notice('Activity trust could not be achieved.', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
209 if (empty($object_data)) {
210 Logger::notice('No object data found', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
214 if (self::routeActivities($object_data, $type, true)) {
215 Logger::debug('Handled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]);
217 Logger::info('Unhandled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
222 $contact = Contact::getByURL($actor);
223 if (empty($contact)) {
224 Logger::info('Relay contact not found', ['actor' => $actor]);
228 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
229 Logger::notice('Relay is no sharer', ['actor' => $actor]);
233 Logger::debug('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
235 $item_id = Item::searchByLink($object_id);
237 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
241 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
243 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
249 * Fetches the object type for a given object id
251 * @param array $activity
252 * @param string $object_id Object ID of the provided object
253 * @param integer $uid User ID
255 * @return string with object type or NULL
256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
257 * @throws \ImagickException
259 public static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
261 if (!empty($activity['as:object'])) {
262 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
263 if (!empty($object_type)) {
268 if (Post::exists(['uri' => $object_id, 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]])) {
269 // We just assume "note" since it doesn't make a difference for the further processing
273 $profile = APContact::getByURL($object_id);
274 if (!empty($profile['type'])) {
275 APContact::unmarkForArchival($profile);
276 return 'as:' . $profile['type'];
279 $data = Processor::fetchCachedActivity($object_id, $uid);
281 $object = JsonLD::compact($data);
282 $type = JsonLD::fetchElement($object, '@type');
292 * Prepare the object array
294 * @param array $activity Array with activity data
295 * @param integer $uid User ID
296 * @param boolean $push Message had been pushed to our system
297 * @param boolean $trust_source Do we trust the source?
298 * @param string $original_actor Actor of the original activity. Used for receiver detection. (Optional)
300 * @return array with object data
301 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
302 * @throws \ImagickException
304 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source, string $original_actor = ''): array
306 $id = JsonLD::fetchElement($activity, '@id');
307 $type = JsonLD::fetchElement($activity, '@type');
308 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
310 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
311 $fetch_id = $object_id;
316 if (!empty($activity['as:object'])) {
317 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
322 if (!empty($id) && !$trust_source) {
323 $fetch_uid = $uid ?: self::getBestUserForActivity($activity, $original_actor);
325 $fetched_activity = Processor::fetchCachedActivity($fetch_id, $fetch_uid);
326 if (!empty($fetched_activity)) {
328 $object = JsonLD::compact($fetched_activity);
330 $fetched_id = JsonLD::fetchElement($object, '@id');
331 $fetched_type = JsonLD::fetchElement($object, '@type');
333 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
334 Logger::info('Activity had been fetched successfully', ['id' => $id]);
335 $trust_source = true;
337 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
338 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
339 $trust_source = true;
340 unset($object['@context']);
341 $activity['as:object'] = $object;
343 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
346 Logger::info('Activity could not been fetched', ['id' => $id]);
350 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
352 Logger::info('Empty actor', ['activity' => $activity]);
356 $type = JsonLD::fetchElement($activity, '@type');
358 // Fetch all receivers from to, cc, bto and bcc
359 $receiverdata = self::getReceivers($activity, $original_actor ?: $actor, [], false, $push || $fetched);
360 $receivers = $reception_types = [];
361 foreach ($receiverdata as $key => $data) {
362 $receivers[$key] = $data['uid'];
363 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
366 $urls = self::getReceiverURL($activity);
368 // When it is a delivery to a personal inbox we add that user to the receivers
370 $additional = [$uid => $uid];
371 $receivers = array_replace($receivers, $additional);
372 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]))) {
373 $reception_types[$uid] = self::TARGET_BCC;
374 $owner = User::getOwnerDataById($uid);
375 if (!empty($owner['url'])) {
376 $urls['as:bcc'][] = $owner['url'];
381 // We possibly need some user to fetch private content,
382 // so we fetch one out of the receivers if no uid is provided.
383 $fetch_uid = $uid ?: self::getBestUserForActivity($activity, $original_actor);
385 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
386 if (empty($object_id)) {
387 Logger::info('No object found');
391 if (!is_string($object_id)) {
392 Logger::info('Invalid object id', ['object' => $object_id]);
396 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
398 // Any activities on account types must not be altered
399 if (in_array($type, ['as:Flag'])) {
401 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
402 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
403 $object_data['object_ids'] = JsonLD::fetchElementArray($activity, 'as:object', '@id');
404 $object_data['content'] = JsonLD::fetchElement($activity, 'as:content', '@type');
405 } elseif (in_array($object_type, self::ACCOUNT_TYPES)) {
407 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
408 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
409 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
410 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
411 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
412 if (!$trust_source && ($type == 'as:Delete')) {
413 $apcontact = APContact::getByURL($object_data['object_id'], true);
414 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
416 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Invite']) || strpos($type, '#emojiReaction')) {
417 // Fetch the content only on activities where this matters
418 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
419 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $fetch_uid);
420 if (empty($object_data)) {
421 Logger::info("Object data couldn't be processed");
425 $object_data['object_id'] = $object_id;
427 // Test if it is an answer to a mail
428 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
429 $object_data['directmessage'] = true;
431 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
433 if (!empty(JsonLD::fetchElement($activity['as:object'], 'misskey:_misskey_talk'))) {
434 $object_data = self::setChatData($object_data, $receivers);
437 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
438 // Create a mostly empty array out of the activity data (instead of the object).
439 // This way we later don't have to check for the existence of each individual array element.
440 $object_data = self::processObject($activity, $original_actor);
441 $object_data['name'] = $type;
442 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
443 $object_data['object_id'] = $object_id;
444 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
445 } elseif (in_array($type, ['as:Add', 'as:Remove', 'as:Move'])) {
447 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
448 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
449 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
450 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
451 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
454 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
455 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
456 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
457 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
458 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
460 // An Undo is done on the object of an object, so we need that type as well
461 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
462 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
465 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
466 $trust_source = Processor::isActivityGone($object_data['object_id']);
467 if (!$trust_source) {
468 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
473 $object_data['push'] = $push;
475 $object_data = self::addActivityFields($object_data, $activity);
477 if (empty($object_data['object_type'])) {
478 $object_data['object_type'] = $object_type;
481 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience', 'as:attributedTo'] as $element) {
482 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
483 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
487 $object_data['type'] = $type;
488 $object_data['actor'] = $actor;
489 $object_data['item_receiver'] = $receivers;
490 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
491 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
493 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
494 // $author = $object_data['author'] ?? $actor;
495 // if (!empty($author) && !empty($object_data['id'])) {
496 // $author_host = parse_url($author, PHP_URL_HOST);
497 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
498 // if ($author_host == $id_host) {
499 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
501 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
502 // $trust_source = false;
506 $account = Contact::selectFirstAccount(['platform'], ['nurl' => Strings::normaliseLink($actor)]);
507 $platform = $account['platform'] ?? '';
509 Logger::info('Processing', ['type' => $object_data['type'], 'object_type' => $object_data['object_type'], 'id' => $object_data['id'], 'actor' => $actor, 'platform' => $platform]);
514 private static function setChatData(array $object_data, array $receivers): array
516 if (count($receivers) != 1) {
520 $user = User::getById(array_key_first($receivers), ['language']);
521 $l10n = DI::l10n()->withLang($user['language']);
522 $object_data['name'] = $l10n->t('Chat');
524 $mail = DBA::selectFirst('mail', ['uri'], ['uid' => array_key_first($receivers), 'title' => $object_data['name']], ['order' => ['id' => true]]);
525 if (!empty($mail['uri'])) {
526 $object_data['reply-to-id'] = $mail['uri'];
529 $object_data['directmessage'] = true;
530 Logger::debug('Got Misskey Chat');
535 * Fetches the first user id from the receiver array
537 * @param array $receivers Array with receivers
538 * @return integer user id;
540 public static function getFirstUserFromReceivers(array $receivers): int
542 foreach ($receivers as $receiver) {
543 if (!empty($receiver)) {
551 * Processes the activity object
553 * @param array $activity Array with activity data
554 * @param string $body The unprocessed body
555 * @param int|null $uid User ID
556 * @param boolean $trust_source Do we trust the source?
557 * @param boolean $push Message had been pushed to our system
558 * @param array $signer The signer of the post
562 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
563 * @throws \ImagickException
565 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
567 $type = JsonLD::fetchElement($activity, '@type');
569 Logger::info('Empty type', ['activity' => $activity]);
573 if (!DI::config()->get('system', 'process_view') && ($type == 'as:View')) {
574 Logger::info('View activities are ignored.', ['signer' => $signer, 'http_signer' => $http_signer]);
578 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
579 Logger::info('Empty object', ['activity' => $activity]);
583 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
585 Logger::info('Empty actor', ['activity' => $activity]);
589 if (is_array($activity['as:object'])) {
590 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
595 // Test the provided signatures against the actor and "attributedTo"
597 if (!empty($attributed_to) && !empty($actor)) {
598 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
600 $trust_source = in_array($actor, $signer);
604 // Lemmy announces activities.
605 // To simplify the further processing, we modify the received object.
606 // For announced "create" activities we remove the middle layer.
607 // For the rest (like, dislike, update, ...) we just process the activity directly.
608 $original_actor = '';
609 $object_type = JsonLD::fetchElement($activity['as:object'] ?? [], '@type');
610 if (($type == 'as:Announce') && !empty($object_type) && !in_array($object_type, self::CONTENT_TYPES) && self::isGroup($actor)) {
611 $object_object_type = JsonLD::fetchElement($activity['as:object']['as:object'] ?? [], '@type');
612 if (in_array($object_type, ['as:Create']) && in_array($object_object_type, self::CONTENT_TYPES)) {
613 Logger::debug('Replace "create" activity with inner object', ['type' => $object_type, 'object_type' => $object_object_type]);
614 $activity['as:object'] = $activity['as:object']['as:object'];
615 } elseif (in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
616 Logger::debug('Change announced activity to activity', ['type' => $object_type]);
617 $original_actor = $actor;
618 $type = $object_type;
619 $activity = $activity['as:object'];
621 Logger::info('Unhandled announced activity', ['type' => $object_type, 'object_type' => $object_object_type]);
625 // $trust_source is called by reference and is set to true if the content was retrieved successfully
626 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source, $original_actor);
627 if (empty($object_data)) {
628 Logger::info('No object data found', ['activity' => $activity]);
632 if (!empty($body) && empty($object_data['raw'])) {
633 $object_data['raw'] = $body;
636 // Internal flag for thread completion. See Processor.php
637 if (!empty($activity['thread-completion'])) {
638 $object_data['thread-completion'] = $activity['thread-completion'];
641 if (!empty($activity['completion-mode'])) {
642 $object_data['completion-mode'] = $activity['completion-mode'];
645 if (!empty($activity['thread-children-type'])) {
646 $object_data['thread-children-type'] = $activity['thread-children-type'];
649 // Internal flag for posts that arrived via relay
650 if (!empty($activity['from-relay'])) {
651 $object_data['from-relay'] = $activity['from-relay'];
654 if ($type == 'as:Announce') {
655 $object_data['object_activity'] = $activity;
658 if (($type == 'as:Create') && $trust_source && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE])) {
659 if (self::hasArrived($object_data['object_id'])) {
660 Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]);
663 self::addArrivedId($object_data['object_id']);
665 if (Queue::exists($object_data['object_id'], $type)) {
666 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
669 } elseif (($type == 'as:Create') && $trust_source && !self::hasArrived($object_data['object_id'])) {
670 self::addArrivedId($object_data['object_id']);
673 $decouple = DI::config()->get('system', 'decoupled_receiver') && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE]);
675 if ($decouple && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
676 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
679 if (!$trust_source) {
680 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
684 if (!empty($object_data['entry-id']) && $decouple && ($push || ($completion == self::COMPLETION_RELAY))) {
685 if (Queue::isProcessable($object_data['entry-id'])) {
686 // We delay by 5 seconds to allow to accumulate all receivers
687 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
688 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
689 $wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
690 Queue::setWorkerId($object_data['entry-id'], $wid);
692 Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]);
697 if (!empty($activity['recursion-depth'])) {
698 $object_data['recursion-depth'] = $activity['recursion-depth'];
701 if (!self::routeActivities($object_data, $type, $push, true, $uid)) {
702 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
703 Queue::remove($object_data);
709 * Checks if the provided actor is a group account
711 * @param string $actor
714 private static function isGroup(string $actor): bool
716 $profile = APContact::getByURL($actor);
717 return ($profile['type'] ?? '') == 'Group';
723 * @param array $object_data
724 * @param string $type
726 * @param bool $fetch_parents
729 * @return boolean Could the activity be routed?
731 public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true, int $uid = 0): bool
735 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
736 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
737 ActivityPub\Processor::postItem($object_data, $item);
738 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
739 // Unhandled Peertube activity
740 Queue::remove($object_data);
741 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
742 ActivityPub\Processor::updatePerson($object_data);
749 if (in_array($object_data['object_type'], ['as:Event'])) {
750 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
751 ActivityPub\Processor::postItem($object_data, $item);
758 if ($object_data['object_type'] == 'as:tag') {
759 ActivityPub\Processor::addTag($object_data);
760 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
761 ActivityPub\Processor::addToFeaturedCollection($object_data);
762 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
763 // We don't have the object here or it is deleted. We ignore this activity.
764 Queue::remove($object_data);
771 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
772 if (!Item::searchByLink($object_data['object_id'], $uid)) {
773 if (ActivityPub\Processor::fetchMissingActivity($object_data['object_id'], [], $object_data['actor'], self::COMPLETION_ANNOUNCE, $uid)) {
774 Logger::debug('Created announced id', ['uid' => $uid, 'id' => $object_data['object_id']]);
775 Queue::remove($object_data);
777 Logger::debug('Announced id was not created', ['uid' => $uid, 'id' => $object_data['object_id']]);
778 Queue::remove($object_data);
782 Logger::info('Announced id already exists', ['uid' => $uid, 'id' => $object_data['object_id']]);
783 Queue::remove($object_data);
786 ActivityPub\Processor::createActivity($object_data, Activity::ANNOUNCE);
787 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
788 // We don't have the object here or it is deleted. We ignore this activity.
789 Queue::remove($object_data);
796 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
797 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
798 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
799 // We don't have the object here or it is deleted. We ignore this activity.
800 Queue::remove($object_data);
807 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
808 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
809 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
810 // We don't have the object here or it is deleted. We ignore this activity.
811 Queue::remove($object_data);
817 case 'as:TentativeAccept':
818 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
819 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
826 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
827 ActivityPub\Processor::updateItem($object_data);
828 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
829 ActivityPub\Processor::updatePerson($object_data);
830 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
831 // Unhandled Peertube activity
832 Queue::remove($object_data);
839 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
840 ActivityPub\Processor::deleteItem($object_data);
841 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
842 ActivityPub\Processor::deletePerson($object_data);
843 } elseif ($object_data['object_type'] == '') {
844 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
845 Queue::remove($object_data);
852 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
853 ActivityPub\Processor::movePerson($object_data);
860 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
861 ActivityPub\Processor::blockAccount($object_data);
868 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
869 ActivityPub\Processor::ReportAccount($object_data);
876 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
877 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
878 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
879 // We don't have the object here or it is deleted. We ignore this activity.
880 Queue::remove($object_data);
887 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
888 ActivityPub\Processor::followUser($object_data);
889 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
890 $object_data['reply-to-id'] = $object_data['object_id'];
891 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
898 if ($object_data['object_type'] == 'as:Follow') {
899 if (!empty($object_data['object_actor'])) {
900 ActivityPub\Processor::acceptFollowUser($object_data);
902 Logger::notice('Unhandled "accept follow" message.', ['object_data' => $object_data]);
904 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
905 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
906 } elseif (!empty($object_data['object_id']) && empty($object_data['object_actor']) && empty($object_data['object_type'])) {
907 // Follow acceptances from gup.pe only contain the object id
908 ActivityPub\Processor::acceptFollowUser($object_data);
915 if ($object_data['object_type'] == 'as:Follow') {
916 ActivityPub\Processor::rejectFollowUser($object_data);
917 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
918 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
925 if (($object_data['object_type'] == 'as:Follow') &&
926 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
927 ActivityPub\Processor::undoFollowUser($object_data);
928 } elseif (($object_data['object_type'] == 'as:Follow') &&
929 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
930 ActivityPub\Processor::undoActivity($object_data);
931 } elseif (($object_data['object_type'] == 'as:Accept') &&
932 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
933 ActivityPub\Processor::rejectFollowUser($object_data);
934 } elseif (($object_data['object_type'] == 'as:Block') &&
935 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
936 ActivityPub\Processor::unblockAccount($object_data);
937 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
938 empty($object_data['object_object_type'])) {
939 // We cannot detect the target object. So we can ignore it.
940 Queue::remove($object_data);
941 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
942 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
943 ActivityPub\Processor::undoActivity($object_data);
944 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
945 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
946 // Unhandled Peertube activity
947 Queue::remove($object_data);
948 } elseif (in_array($object_data['object_type'], ['as:Delete'])) {
949 // We cannot undo deletions, so we just ignore this
950 Queue::remove($object_data);
951 } elseif (in_array($object_data['object_object_type'], ['as:Tombstone'])) {
952 // The object is a tombstone, we ignore any actions on it.
953 Queue::remove($object_data);
960 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
961 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
962 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
963 // We don't have the object here or it is deleted. We ignore this activity.
964 Queue::remove($object_data);
970 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
971 ActivityPub\Processor::createActivity($object_data, Activity::READ);
972 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
973 // We don't have the object here or it is deleted. We ignore this activity.
974 Queue::remove($object_data);
980 case 'litepub:EmojiReact':
981 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
982 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
983 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
984 // We don't have the object here or it is deleted. We ignore this activity.
985 Queue::remove($object_data);
992 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
999 * Stores unhandled or unknown Activities as a file
1001 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
1002 * @param string $type Activity type
1003 * @param array $object_data Preprocessed array that is generated out of the received activity
1004 * @param array $activity Array with activity data
1005 * @param string $body The unprocessed body
1006 * @param integer $uid User ID
1007 * @param boolean $trust_source Do we trust the source?
1008 * @param boolean $push Message had been pushed to our system
1009 * @param array $signer The signer of the post
1012 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 = [])
1014 if (!DI::config()->get('debug', 'ap_log_unknown')) {
1018 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
1020 if (!empty($object_data['object_type'])) {
1021 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
1024 if (!empty($object_data['object_object_type'])) {
1025 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
1028 $tempfile = tempnam(System::getTempPath(), $file);
1029 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));
1030 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], 'object_object_type' => $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
1034 * Fetch a user id from an activity array
1036 * @param array $activity
1037 * @param string $actor
1039 * @return int user id
1041 public static function getBestUserForActivity(array $activity, string $actor = ''): int
1044 $actor = $actor ?: JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
1046 $receivers = self::getReceivers($activity, $actor, [], false, false);
1047 foreach ($receivers as $receiver) {
1048 if ($receiver['type'] == self::TARGET_GLOBAL) {
1051 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
1052 $uid = $receiver['uid'];
1056 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
1058 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
1059 if (!empty($contact['uid'])) {
1060 $uid = $contact['uid'];
1067 // @TODO Missing documentation
1068 public static function getReceiverURL(array $activity): array
1072 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc', 'as:audience', 'as:attributedTo'] as $element) {
1073 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1074 if (empty($receiver_list)) {
1078 foreach ($receiver_list as $receiver) {
1079 if ($receiver == 'Public') {
1080 Logger::warning('Not compacted public collection found', ['activity' => $activity]);
1081 $receiver = ActivityPub::PUBLIC_COLLECTION;
1083 if ($receiver == self::PUBLIC_COLLECTION) {
1084 $receiver = ActivityPub::PUBLIC_COLLECTION;
1086 $urls[$element][] = $receiver;
1094 * Fetch the receiver list from an activity array
1096 * @param array $activity
1097 * @param string $actor
1098 * @param array $tags
1099 * @param bool $fetch_unlisted
1102 * @return array with receivers (user id)
1103 * @throws \Exception
1105 private static function getReceivers(array $activity, string $actor, array $tags, bool $fetch_unlisted, bool $push): array
1107 $reply = $receivers = $profile = [];
1109 // When it is an answer, we inherit the receivers from the parent
1110 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
1111 if (!empty($replyto)) {
1112 $reply = [$replyto];
1114 // Fix possibly wrong item URI (could be an answer to a plink uri)
1115 $fixedReplyTo = Item::getURIByLink($replyto);
1116 if (!empty($fixedReplyTo)) {
1117 $reply[] = $fixedReplyTo;
1121 // Fetch all posts that refer to the object id
1122 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
1123 if (!empty($object_id)) {
1124 $reply[] = $object_id;
1127 if (!empty($actor)) {
1128 $profile = APContact::getByURL($actor);
1129 $followers = $profile['followers'] ?? '';
1130 $isGroup = ($profile['type'] ?? '') == 'Group';
1132 Contact::updateByUrlIfNeeded($actor);
1134 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1136 Logger::info('Empty actor', ['activity' => $activity]);
1141 // We have to prevent false follower assumptions upon thread completions
1142 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1144 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc','as:audience'] as $element) {
1145 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1146 if (empty($receiver_list)) {
1150 foreach ($receiver_list as $receiver) {
1151 if ($receiver == self::PUBLIC_COLLECTION) {
1152 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1155 // Add receiver "-1" for unlisted posts
1156 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1157 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1160 // Fetch the receivers for the public and the followers collection
1161 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$isGroup) || ($isGroup && ($element == 'as:audience'))) && !empty($actor)) {
1162 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1166 // Fetching all directly addressed receivers
1167 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1168 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1169 if (!DBA::isResult($contact)) {
1173 // Check if the potential receiver is following the actor
1174 // Exception: The receiver is targetted via "to" or this is a comment
1175 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1176 $networks = Protocol::FEDERATED;
1177 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1178 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1180 // Group posts are only accepted from group contacts
1181 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1182 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1185 if (!DBA::exists('contact', $condition)) {
1190 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1191 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1194 $type = self::TARGET_TO;
1197 $type = self::TARGET_CC;
1200 $type = self::TARGET_BTO;
1203 $type = self::TARGET_BCC;
1206 $type = self::TARGET_AUDIENCE;
1210 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1215 if (!empty($reply) && (!empty($receivers[0]) || !empty($receivers[-1]))) {
1216 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1217 while ($parent = Post::fetch($parents)) {
1218 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1220 DBA::close($parents);
1223 self::switchContacts($receivers, $actor);
1225 // "birdsitelive" is a service that mirrors tweets into the fediverse
1226 // These posts can be fetched without authentication, but are not marked as public
1227 // We treat them as unlisted posts to be able to handle them.
1228 // We always process deletion activities.
1229 $activity_type = JsonLD::fetchElement($activity, '@type');
1230 if (empty($receivers) && $fetch_unlisted && Contact::isPlatform($actor, 'birdsitelive')) {
1231 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1232 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1233 Logger::notice('Post from "birdsitelive" is set to "unlisted"', ['id' => JsonLD::fetchElement($activity, '@id')]);
1234 } elseif (empty($receivers) && in_array($activity_type, ['as:Delete', 'as:Undo'])) {
1235 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1236 } elseif (empty($receivers)) {
1237 Logger::notice('Post has got no receivers', ['fetch_unlisted' => $fetch_unlisted, 'actor' => $actor, 'id' => JsonLD::fetchElement($activity, '@id'), 'type' => $activity_type]);
1244 * Fetch the receiver list of a given actor
1246 * @param string $actor
1247 * @param array $tags
1248 * @param array $receivers
1249 * @param integer $target_type
1250 * @param array $profile
1252 * @return array with receivers (user id)
1253 * @throws \Exception
1255 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1257 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1258 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1260 if (!empty($profile['uri-id'])) {
1261 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1262 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1263 while ($contact = DBA::fetch($contacts)) {
1264 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1265 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1268 DBA::close($contacts);
1270 // This part will only be called while post update 1426 wasn't finished
1271 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1272 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1273 while ($contact = DBA::fetch($contacts)) {
1274 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1275 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1278 DBA::close($contacts);
1280 // The queries are split because of performance issues
1281 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1282 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1283 while ($contact = DBA::fetch($contacts)) {
1284 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1285 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1288 DBA::close($contacts);
1294 * Tests if the contact is a valid receiver for this actor
1296 * @param array $contact
1297 * @param array $tags
1299 * @return bool with receivers (user id)
1300 * @throws \Exception
1302 private static function isValidReceiverForActor(array $contact, array $tags): bool
1304 // Are we following the contact? Then this is a valid receiver
1305 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1309 // When the possible receiver isn't a community, then it is no valid receiver
1310 $owner = User::getOwnerDataById($contact['uid']);
1311 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1315 // Is the community account tagged?
1316 foreach ($tags as $tag) {
1317 if ($tag['type'] != 'Mention') {
1321 if (Strings::compareLink($tag['href'], $owner['url'])) {
1330 * Switches existing contacts to ActivityPub
1332 * @param integer $cid Contact ID
1333 * @param integer $uid User ID
1334 * @param string $url Profile URL
1336 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1337 * @throws \ImagickException
1339 public static function switchContact(int $cid, int $uid, string $url)
1341 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1342 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1346 if (Contact::updateFromProbe($cid)) {
1347 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1350 // Send a new follow request to be sure that the connection still exists
1351 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1352 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1353 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1358 * @TODO Fix documentation and type-hints
1363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1364 * @throws \ImagickException
1366 private static function switchContacts($receivers, $actor)
1368 if (empty($actor)) {
1372 foreach ($receivers as $receiver) {
1373 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1374 if (DBA::isResult($contact)) {
1375 self::switchContact($contact['id'], $receiver['uid'], $actor);
1378 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1379 if (DBA::isResult($contact)) {
1380 self::switchContact($contact['id'], $receiver['uid'], $actor);
1386 * @TODO Fix documentation and type-hints
1388 * @param $object_data
1389 * @param array $activity
1393 private static function addActivityFields($object_data, array $activity)
1395 if (!empty($activity['published']) && empty($object_data['published'])) {
1396 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1399 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1400 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1403 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1404 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1406 if (!empty($object_data['object_id'])) {
1407 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1408 $objectId = Item::getURIByLink($object_data['object_id']);
1409 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1410 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1411 $object_data['object_id'] = $objectId;
1415 return $object_data;
1419 * Fetches the object data from external resources if needed
1421 * @param string $object_id Object ID of the provided object
1422 * @param array $object The provided object array
1423 * @param boolean $trust_source Do we trust the provided object?
1424 * @param integer $uid User ID for the signature that we use to fetch data
1426 * @return array|false with trusted and valid object data
1427 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1428 * @throws \ImagickException
1430 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1432 // By fetching the type we check if the object is complete.
1433 $type = JsonLD::fetchElement($object, '@type');
1435 if (!$trust_source || empty($type)) {
1436 $data = Processor::fetchCachedActivity($object_id, $uid);
1437 if (!empty($data)) {
1438 $object = JsonLD::compact($data);
1439 Logger::info('Fetched content for ' . $object_id);
1441 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1443 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1444 if (!DBA::isResult($item)) {
1445 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1448 Logger::info('Using already stored item for url ' . $object_id);
1449 $data = ActivityPub\Transmitter::createNote($item);
1450 $object = JsonLD::compact($data);
1453 $id = JsonLD::fetchElement($object, '@id');
1455 Logger::info('Empty id');
1459 if ($id != $object_id) {
1460 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1464 Logger::info('Using original object for url ' . $object_id);
1467 $type = JsonLD::fetchElement($object, '@type');
1469 Logger::info('Empty type');
1473 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1474 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1475 $object_data = self::processObject($object, '');
1477 if (!empty($data)) {
1478 $object_data['raw-object'] = json_encode($data);
1480 return $object_data;
1483 Logger::info('Unhandled object type: ' . $type);
1488 * Converts the language element (Used by Peertube)
1490 * @param array $languages
1491 * @return array Languages
1493 public static function processLanguages(array $languages): array
1495 if (empty($languages)) {
1499 $language_list = [];
1501 foreach ($languages as $language) {
1502 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1503 $language_list[$language['_:identifier']] = $language['as:name'];
1506 return $language_list;
1510 * Convert tags from JSON-LD format into a simplified format
1512 * @param array $tags Tags in JSON-LD format
1514 * @return array with tags in a simplified format
1516 public static function processTags(array $tags): array
1520 foreach ($tags as $tag) {
1525 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type') ?? ''),
1526 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1527 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1529 if (empty($element['type'])) {
1533 if (empty($element['href'])) {
1534 $element['href'] = $element['name'];
1537 $taglist[] = $element;
1543 * Convert emojis from JSON-LD format into a simplified format
1545 * @param array $emojis
1546 * @return array with emojis in a simplified format
1548 private static function processEmojis(array $emojis): array
1552 foreach ($emojis as $emoji) {
1553 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1557 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1558 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1561 $emojilist[] = $element;
1568 * Convert attachments from JSON-LD format into a simplified format
1570 * @param array $attachments Attachments in JSON-LD format
1572 * @return array Attachments in a simplified format
1574 private static function processAttachments(array $attachments): array
1578 // Removes empty values
1579 $attachments = array_filter($attachments);
1581 foreach ($attachments as $attachment) {
1582 switch (JsonLD::fetchElement($attachment, '@type')) {
1587 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1588 foreach ($urls as $url) {
1589 // Single scalar URL case
1590 if (is_string($url)) {
1595 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1596 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1597 if (Strings::startsWith($mediaType, 'image')) {
1606 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1607 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1609 'image' => $pageImage,
1613 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1614 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1615 $imagePreviewUrl = null;
1617 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1618 $imageVariants = [];
1619 $previewVariants = [];
1620 foreach ($urls as $url) {
1621 // Scalar URL, no discrimination possible
1622 if (is_string($url)) {
1623 $imageFullUrl = $url;
1627 // Not sure what to do with a different Link media type than the base Image, we skip
1628 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1632 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1634 // Default URL choice if no discriminating width is provided
1635 $imageFullUrl = $href ?? $imageFullUrl;
1637 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1639 if ($href && $width) {
1640 $imageVariants[$width] = $href;
1641 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1642 $previewVariants[abs(632 - $width)] = $href;
1646 if ($imageVariants) {
1647 // Taking the maximum size image
1648 ksort($imageVariants);
1649 $imageFullUrl = array_pop($imageVariants);
1651 // Taking the minimum number distance to the target distance
1652 ksort($previewVariants);
1653 $imagePreviewUrl = array_shift($previewVariants);
1656 unset($imageVariants);
1657 unset($previewVariants);
1661 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1662 'mediaType' => $mediaType,
1663 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1664 'url' => $imageFullUrl,
1665 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1670 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1671 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1672 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1673 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id') ?? JsonLD::fetchElement($attachment, 'as:href', '@id'),
1674 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1675 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1676 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1685 * Convert questions from JSON-LD format into a simplified format
1687 * @param array $object
1689 * @return array Questions in a simplified format
1691 private static function processQuestion(array $object): array
1695 if (!empty($object['as:oneOf'])) {
1696 $question['multiple'] = false;
1697 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1698 } elseif (!empty($object['as:anyOf'])) {
1699 $question['multiple'] = true;
1700 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1705 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1706 if (!empty($closed)) {
1707 $question['end-time'] = $closed;
1709 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1712 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1713 $question['options'] = [];
1717 foreach ($options as $option) {
1718 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1722 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1724 if (empty($option['as:replies'])) {
1728 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1730 $question['options'][] = ['name' => $name, 'replies' => $replies];
1732 $voters += (int)$replies;
1735 // For single choice question we can count the number of voters if not provided (like with Misskey)
1736 if (empty($question['voters']) && !$question['multiple']) {
1737 $question['voters'] = $voters;
1744 * Fetch the original source or content with the "language" Markdown or HTML
1746 * @param array $object
1747 * @param array $object_data
1749 * @return array Object data (?)
1750 * @throws \Exception
1752 private static function getSource(array $object, array $object_data): array
1754 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1755 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1756 if (!empty($object_data['source'])) {
1757 return $object_data;
1760 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1761 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1762 if (!empty($object_data['source'])) {
1763 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1764 return $object_data;
1767 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1768 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1769 if (!empty($object_data['source'])) {
1770 $object_data['source'] = HTML::toBBCode($object_data['source']);
1771 return $object_data;
1774 return $object_data;
1778 * Extracts a potential alternate URL from a list of additional URL elements
1780 * @param array $urls
1783 private static function extractAlternateUrl(array $urls): string
1786 foreach ($urls as $key => $url) {
1787 // Not a list but a single URL element
1788 if (!is_numeric($key)) {
1792 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1796 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1801 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1802 if (empty($mediatype)) {
1806 if ($mediatype == 'text/html') {
1807 $alternateUrl = $href;
1811 return $alternateUrl;
1815 * Check if the "as:url" element is an array with multiple links
1816 * This is the case with audio and video posts.
1817 * Then the links are added as attachments
1819 * @param array $urls The object URL list
1820 * @return array an array of attachments
1822 private static function processAttachmentUrls(array $urls): array
1825 foreach ($urls as $key => $url) {
1826 // Not a list but a single URL element
1827 if (!is_numeric($key)) {
1831 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1835 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1840 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1841 if (empty($mediatype)) {
1845 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1847 if ($filetype == 'audio') {
1848 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1849 } elseif ($filetype == 'video') {
1850 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1851 // PeerTube audio-only track
1852 if ($height === 0) {
1856 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1857 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1858 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1859 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1861 // For Torrent links we always store the highest resolution
1862 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1866 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1867 } elseif ($mediatype == 'application/x-mpegURL') {
1868 // PeerTube exception, actual video link is in the tags of this URL element
1869 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1873 return array_values($attachments);
1877 * Fetches data from the object part of an activity
1879 * @param array $object
1880 * @param string $actor
1882 * @return array|bool Object data or FALSE if $object does not contain @id element
1883 * @throws \Exception
1885 private static function processObject(array $object, string $actor)
1887 if (!JsonLD::fetchElement($object, '@id')) {
1891 $object_data = self::getObjectDataFromActivity($object);
1893 $receiverdata = self::getReceivers($object, $actor ?: $object_data['actor'] ?? '', $object_data['tags'], true, false);
1894 $receivers = $reception_types = [];
1895 foreach ($receiverdata as $key => $data) {
1896 $receivers[$key] = $data['uid'];
1897 $reception_types[$data['uid']] = $data['type'] ?? 0;
1900 $object_data['receiver_urls'] = self::getReceiverURL($object);
1901 $object_data['receiver'] = $receivers;
1902 $object_data['reception_type'] = $reception_types;
1904 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1905 unset($object_data['receiver'][-1]);
1906 unset($object_data['reception_type'][-1]);
1908 return $object_data;
1912 * Create an object data array from a given activity
1914 * @param array $object
1916 * @return array Object data
1918 public static function getObjectDataFromActivity(array $object): array
1921 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1922 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1923 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1925 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1926 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1927 $object_data['reply-to-id'] = $object_data['id'];
1929 // On activities the "reply to" is the id of the object it refers to
1930 if (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce']))) {
1931 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1932 if (!empty($object_id)) {
1933 $object_data['reply-to-id'] = $object_id;
1937 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1938 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1939 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1940 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1941 $object_data['reply-to-id'] = $replyToId;
1945 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1946 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1948 if (empty($object_data['updated'])) {
1949 $object_data['updated'] = $object_data['published'];
1952 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1953 $object_data['published'] = $object_data['updated'];
1956 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1957 if (empty($actor)) {
1958 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1961 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1962 $location = JsonLD::fetchElement($location, 'location', '@value');
1964 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1965 // down to HTML and then finally format to plaintext.
1966 $location = Markdown::convert($location);
1967 $location = BBCode::toPlaintext($location);
1970 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1971 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1972 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1973 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1974 $object_data['actor'] = $object_data['author'] = $actor;
1975 $element = JsonLD::fetchElement($object, 'as:context', '@id');
1976 $object_data['context'] = $element != './' ? $element : null;
1977 $element = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1978 $object_data['conversation'] = $element != './' ? $element : null;
1979 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1980 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1981 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1982 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1983 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1984 $object_data = self::getSource($object, $object_data);
1985 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1986 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1987 $object_data['location'] = $location;
1988 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1989 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1990 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1991 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1992 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1993 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1994 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1995 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1996 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1997 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1998 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
2000 // Special treatment for Hubzilla links
2001 if (is_array($object_data['alternate-url'])) {
2002 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
2004 if (!is_string($object_data['alternate-url'])) {
2005 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
2009 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
2010 $object_data['alternate-url'] = null;
2013 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
2014 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
2015 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
2018 // Support for quoted posts (Pleroma, Fedibird and Misskey)
2019 $object_data['quote-url'] = JsonLD::fetchElement($object, 'as:quoteUrl', '@value');
2020 if (empty($object_data['quote-url'])) {
2021 $object_data['quote-url'] = JsonLD::fetchElement($object, 'fedibird:quoteUri', '@value');
2023 if (empty($object_data['quote-url'])) {
2024 $object_data['quote-url'] = JsonLD::fetchElement($object, 'misskey:_misskey_quote', '@value');
2027 // Misskey adds some data to the standard "content" value for quoted posts for backwards compatibility.
2028 // Their own "_misskey_content" value does then contain the content without this extra data.
2029 if (!empty($object_data['quote-url'])) {
2030 $misskey_content = JsonLD::fetchElement($object, 'misskey:_misskey_content', '@value');
2031 if (!empty($misskey_content)) {
2032 $object_data['content'] = $misskey_content;
2036 // For page types we expect that the alternate url posts to some page.
2037 // So we add this to the attachments if it differs from the id.
2038 // Currently only Lemmy is using the page type.
2039 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
2040 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
2041 $object_data['alternate-url'] = null;
2044 if ($object_data['object_type'] == 'as:Question') {
2045 $object_data['question'] = self::processQuestion($object);
2048 return $object_data;
2052 * Add an object id to the list of arrived activities
2058 private static function addArrivedId(string $id)
2060 DBA::delete('arrived-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
2061 DBA::insert('arrived-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE);
2065 * Checks if the given object already arrived before
2071 private static function hasArrived(string $id): bool
2073 return DBA::exists('arrived-activity', ['object-id' => $id]);