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;
77 const COMPLETION_NONE = 0;
78 const COMPLETION_ANNOUNCE = 1;
79 const COMPLETION_RELAY = 2;
80 const COMPLETION_MANUAL = 3;
81 const COMPLETION_AUTO = 4;
84 * Checks incoming message from the inbox
86 * @param string $body Body string
87 * @param array $header Header lines
88 * @param integer $uid User ID
92 public static function processInbox(string $body, array $header, int $uid)
94 $activity = json_decode($body, true);
95 if (empty($activity)) {
96 Logger::warning('Invalid body.');
100 $ldactivity = JsonLD::compact($activity);
102 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
104 $apcontact = APContact::getByURL($actor);
106 if (empty($apcontact)) {
107 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
109 } elseif (APContact::isRelay($apcontact)) {
110 self::processRelayPost($ldactivity, $actor);
113 APContact::unmarkForArchival($apcontact);
116 $sig_contact = HTTPSignature::getKeyIdContact($header);
117 if (APContact::isRelay($sig_contact)) {
118 Logger::info('Message from a relay', ['url' => $sig_contact['url']]);
119 self::processRelayPost($ldactivity, $sig_contact['url']);
123 $http_signer = HTTPSignature::getSigner($body, $header);
124 if ($http_signer === false) {
125 Logger::notice('Invalid HTTP signature, message will not be trusted.', ['uid' => $uid, 'actor' => $actor, 'header' => $header, 'body' => $body]);
127 } elseif (empty($http_signer)) {
128 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
131 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
132 $signer = [$http_signer];
135 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
137 if ($http_signer === false) {
138 $trust_source = false;
139 } elseif (LDSignature::isSigned($activity)) {
140 $ld_signer = LDSignature::getSigner($activity);
141 if (empty($ld_signer)) {
142 Logger::info('Invalid JSON-LD signature from ' . $actor);
143 } elseif ($ld_signer != $http_signer) {
144 $signer[] = $ld_signer;
146 if (!empty($ld_signer && ($actor == $http_signer))) {
147 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
148 $trust_source = true;
149 } elseif (!empty($ld_signer)) {
150 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
151 $trust_source = true;
152 } elseif ($actor == $http_signer) {
153 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
154 $trust_source = true;
156 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
157 $trust_source = false;
159 } elseif ($actor == $http_signer) {
160 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
161 $trust_source = true;
163 Logger::info('No JSON-LD signature, different actor.');
164 $trust_source = false;
167 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
171 * Process incoming posts from relays
173 * @param array $activity
174 * @param string $actor
177 private static function processRelayPost(array $activity, string $actor)
179 $type = JsonLD::fetchElement($activity, '@type');
181 Logger::notice('Empty type', ['activity' => $activity, 'actor' => $actor]);
185 $object_type = JsonLD::fetchElement($activity, 'as:object', '@type') ?? '';
187 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
188 if (empty($object_id)) {
189 Logger::notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]);
193 $handle = ($type == 'as:Announce');
195 if (!$handle && in_array($type, ['as:Create', 'as:Update'])) {
196 $handle = in_array($object_type, self::CONTENT_TYPES);
200 $trust_source = false;
201 $object_data = self::prepareObjectData($activity, 0, false, $trust_source);
203 if (!$trust_source) {
204 Logger::notice('Activity trust could not be achieved.', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
208 if (empty($object_data)) {
209 Logger::notice('No object data found', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
213 if (self::routeActivities($object_data, $type, true)) {
214 Logger::debug('Handled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]);
216 Logger::info('Unhandled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
221 $contact = Contact::getByURL($actor);
222 if (empty($contact)) {
223 Logger::info('Relay contact not found', ['actor' => $actor]);
227 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
228 Logger::notice('Relay is no sharer', ['actor' => $actor]);
232 Logger::debug('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
234 $item_id = Item::searchByLink($object_id);
236 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
240 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
242 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
248 * Fetches the object type for a given object id
250 * @param array $activity
251 * @param string $object_id Object ID of the provided object
252 * @param integer $uid User ID
254 * @return string with object type or NULL
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 * @throws \ImagickException
258 public static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
260 if (!empty($activity['as:object'])) {
261 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
262 if (!empty($object_type)) {
267 if (Post::exists(['uri' => $object_id, 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]])) {
268 // We just assume "note" since it doesn't make a difference for the further processing
272 $profile = APContact::getByURL($object_id);
273 if (!empty($profile['type'])) {
274 APContact::unmarkForArchival($profile);
275 return 'as:' . $profile['type'];
278 $data = Processor::fetchCachedActivity($object_id, $uid);
280 $object = JsonLD::compact($data);
281 $type = JsonLD::fetchElement($object, '@type');
291 * Prepare the object array
293 * @param array $activity Array with activity data
294 * @param integer $uid User ID
295 * @param boolean $push Message had been pushed to our system
296 * @param boolean $trust_source Do we trust the source?
298 * @return array with object data
299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
300 * @throws \ImagickException
302 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
304 $id = JsonLD::fetchElement($activity, '@id');
305 $type = JsonLD::fetchElement($activity, '@type');
306 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
308 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
309 $fetch_id = $object_id;
314 if (!empty($activity['as:object'])) {
315 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
320 if (!empty($id) && !$trust_source) {
321 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
323 $fetched_activity = Processor::fetchCachedActivity($fetch_id, $fetch_uid);
324 if (!empty($fetched_activity)) {
326 $object = JsonLD::compact($fetched_activity);
328 $fetched_id = JsonLD::fetchElement($object, '@id');
329 $fetched_type = JsonLD::fetchElement($object, '@type');
331 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
332 Logger::info('Activity had been fetched successfully', ['id' => $id]);
333 $trust_source = true;
335 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
336 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
337 $trust_source = true;
338 unset($object['@context']);
339 $activity['as:object'] = $object;
341 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
344 Logger::info('Activity could not been fetched', ['id' => $id]);
348 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
350 Logger::info('Empty actor', ['activity' => $activity]);
354 $type = JsonLD::fetchElement($activity, '@type');
356 // Fetch all receivers from to, cc, bto and bcc
357 $receiverdata = self::getReceivers($activity, $actor, [], false, $push || $fetched);
358 $receivers = $reception_types = [];
359 foreach ($receiverdata as $key => $data) {
360 $receivers[$key] = $data['uid'];
361 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
364 $urls = self::getReceiverURL($activity);
366 // When it is a delivery to a personal inbox we add that user to the receivers
368 $additional = [$uid => $uid];
369 $receivers = array_replace($receivers, $additional);
370 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]))) {
371 $reception_types[$uid] = self::TARGET_BCC;
372 $owner = User::getOwnerDataById($uid);
373 if (!empty($owner['url'])) {
374 $urls['as:bcc'][] = $owner['url'];
379 // We possibly need some user to fetch private content,
380 // so we fetch one out of the receivers if no uid is provided.
381 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
383 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
384 if (empty($object_id)) {
385 Logger::info('No object found');
389 if (!is_string($object_id)) {
390 Logger::info('Invalid object id', ['object' => $object_id]);
394 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
396 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
397 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
398 Logger::debug('Fetch announced activity', ['object' => $object_id]);
399 $data = Processor::fetchCachedActivity($object_id, $fetch_uid);
401 $type = $object_type;
402 $activity = JsonLD::compact($data);
404 // Some variables need to be refetched since the activity changed
405 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
406 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
407 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
411 // Any activities on account types must not be altered
412 if (in_array($type, ['as:Flag'])) {
414 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
415 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
416 $object_data['object_ids'] = JsonLD::fetchElementArray($activity, 'as:object', '@id');
417 $object_data['content'] = JsonLD::fetchElement($activity, 'as:content', '@type');
418 } elseif (in_array($object_type, self::ACCOUNT_TYPES)) {
420 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
421 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
422 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
423 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
424 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
425 if (!$trust_source && ($type == 'as:Delete')) {
426 $apcontact = APContact::getByURL($object_data['object_id'], true);
427 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
429 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Invite']) || strpos($type, '#emojiReaction')) {
430 // Fetch the content only on activities where this matters
431 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
432 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source, $fetch_uid);
433 if (empty($object_data)) {
434 Logger::info("Object data couldn't be processed");
438 $object_data['object_id'] = $object_id;
440 // Test if it is an answer to a mail
441 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
442 $object_data['directmessage'] = true;
444 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
446 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Follow'])) && in_array($object_type, self::CONTENT_TYPES)) {
447 // Create a mostly empty array out of the activity data (instead of the object).
448 // This way we later don't have to check for the existence of each individual array element.
449 $object_data = self::processObject($activity);
450 $object_data['name'] = $type;
451 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
452 $object_data['object_id'] = $object_id;
453 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
454 } elseif (in_array($type, ['as:Add', 'as:Remove', 'as:Move'])) {
456 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
457 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
458 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
459 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
460 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
463 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
464 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
465 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
466 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
467 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
469 // An Undo is done on the object of an object, so we need that type as well
470 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
471 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
474 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
475 $trust_source = Processor::isActivityGone($object_data['object_id']);
476 if (!$trust_source) {
477 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
482 $object_data['push'] = $push;
484 $object_data = self::addActivityFields($object_data, $activity);
486 if (empty($object_data['object_type'])) {
487 $object_data['object_type'] = $object_type;
490 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
491 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
492 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
496 $object_data['type'] = $type;
497 $object_data['actor'] = $actor;
498 $object_data['item_receiver'] = $receivers;
499 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
500 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
502 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
503 // $author = $object_data['author'] ?? $actor;
504 // if (!empty($author) && !empty($object_data['id'])) {
505 // $author_host = parse_url($author, PHP_URL_HOST);
506 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
507 // if ($author_host == $id_host) {
508 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
510 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
511 // $trust_source = false;
515 $account = Contact::selectFirstAccount(['platform'], ['nurl' => Strings::normaliseLink($actor)]);
516 $platform = $account['platform'] ?? '';
518 Logger::info('Processing', ['type' => $object_data['type'], 'object_type' => $object_data['object_type'], 'id' => $object_data['id'], 'actor' => $actor, 'platform' => $platform]);
524 * Fetches the first user id from the receiver array
526 * @param array $receivers Array with receivers
527 * @return integer user id;
529 public static function getFirstUserFromReceivers(array $receivers): int
531 foreach ($receivers as $receiver) {
532 if (!empty($receiver)) {
540 * Processes the activity object
542 * @param array $activity Array with activity data
543 * @param string $body The unprocessed body
544 * @param int|null $uid User ID
545 * @param boolean $trust_source Do we trust the source?
546 * @param boolean $push Message had been pushed to our system
547 * @param array $signer The signer of the post
551 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
552 * @throws \ImagickException
554 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
556 $type = JsonLD::fetchElement($activity, '@type');
558 Logger::info('Empty type', ['activity' => $activity]);
562 if (!DI::config()->get('system', 'process_view') && ($type == 'as:View')) {
563 Logger::info('View activities are ignored.', ['signer' => $signer, 'http_signer' => $http_signer]);
567 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
568 Logger::info('Empty object', ['activity' => $activity]);
572 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
574 Logger::info('Empty actor', ['activity' => $activity]);
578 if (is_array($activity['as:object'])) {
579 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
584 // Test the provided signatures against the actor and "attributedTo"
586 if (!empty($attributed_to) && !empty($actor)) {
587 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
589 $trust_source = in_array($actor, $signer);
593 // $trust_source is called by reference and is set to true if the content was retrieved successfully
594 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
595 if (empty($object_data)) {
596 Logger::info('No object data found', ['activity' => $activity]);
600 // Lemmy is announcing activities.
601 // We are changing the announces into regular activities.
602 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
603 Logger::debug('Change type of announce to activity', ['type' => $object_data['type']]);
604 $type = $object_data['type'];
607 if (!empty($body) && empty($object_data['raw'])) {
608 $object_data['raw'] = $body;
611 // Internal flag for thread completion. See Processor.php
612 if (!empty($activity['thread-completion'])) {
613 $object_data['thread-completion'] = $activity['thread-completion'];
616 if (!empty($activity['completion-mode'])) {
617 $object_data['completion-mode'] = $activity['completion-mode'];
620 if (!empty($activity['thread-children-type'])) {
621 $object_data['thread-children-type'] = $activity['thread-children-type'];
624 // Internal flag for posts that arrived via relay
625 if (!empty($activity['from-relay'])) {
626 $object_data['from-relay'] = $activity['from-relay'];
629 if ($type == 'as:Announce') {
630 $object_data['object_activity'] = $activity;
633 if (($type == 'as:Create') && $trust_source && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE])) {
634 if (self::hasArrived($object_data['object_id'])) {
635 Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]);
638 self::addArrivedId($object_data['object_id']);
640 if (Queue::exists($object_data['object_id'], $type)) {
641 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
644 } elseif (($type == 'as:Create') && $trust_source && !self::hasArrived($object_data['object_id'])) {
645 self::addArrivedId($object_data['object_id']);
648 $decouple = DI::config()->get('system', 'decoupled_receiver') && !in_array($completion, [self::COMPLETION_MANUAL, self::COMPLETION_ANNOUNCE]);
650 if ($decouple && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
651 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
654 if (!$trust_source) {
655 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
659 if (!empty($object_data['entry-id']) && $decouple && ($push || ($completion == self::COMPLETION_RELAY))) {
660 if (Queue::isProcessable($object_data['entry-id'])) {
661 // We delay by 5 seconds to allow to accumulate all receivers
662 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
663 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
664 $wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
665 Queue::setWorkerId($object_data['entry-id'], $wid);
667 Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]);
672 if (!empty($activity['recursion-depth'])) {
673 $object_data['recursion-depth'] = $activity['recursion-depth'];
676 if (!self::routeActivities($object_data, $type, $push, true, $uid)) {
677 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
678 Queue::remove($object_data);
686 * @param array $object_data
687 * @param string $type
689 * @param bool $fetch_parents
692 * @return boolean Could the activity be routed?
694 public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true, int $uid = 0): bool
698 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
699 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
700 ActivityPub\Processor::postItem($object_data, $item);
701 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
702 // Unhandled Peertube activity
703 Queue::remove($object_data);
704 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
705 ActivityPub\Processor::updatePerson($object_data);
712 if (in_array($object_data['object_type'], ['as:Event'])) {
713 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
714 ActivityPub\Processor::postItem($object_data, $item);
721 if ($object_data['object_type'] == 'as:tag') {
722 ActivityPub\Processor::addTag($object_data);
723 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
724 ActivityPub\Processor::addToFeaturedCollection($object_data);
725 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
726 // We don't have the object here or it is deleted. We ignore this activity.
727 Queue::remove($object_data);
734 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
735 if (!Item::searchByLink($object_data['object_id'], $uid)) {
736 if (ActivityPub\Processor::fetchMissingActivity($object_data['object_id'], [], $object_data['actor'], self::COMPLETION_ANNOUNCE, $uid)) {
737 Logger::debug('Created announced id', ['uid' => $uid, 'id' => $object_data['object_id']]);
738 Queue::remove($object_data);
740 Logger::debug('Announced id was not created', ['uid' => $uid, 'id' => $object_data['object_id']]);
741 Queue::remove($object_data);
745 Logger::info('Announced id already exists', ['uid' => $uid, 'id' => $object_data['object_id']]);
746 Queue::remove($object_data);
749 ActivityPub\Processor::createActivity($object_data, Activity::ANNOUNCE);
750 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
751 // We don't have the object here or it is deleted. We ignore this activity.
752 Queue::remove($object_data);
759 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
760 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
761 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
762 // We don't have the object here or it is deleted. We ignore this activity.
763 Queue::remove($object_data);
770 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
771 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
772 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
773 // We don't have the object here or it is deleted. We ignore this activity.
774 Queue::remove($object_data);
780 case 'as:TentativeAccept':
781 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
782 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
789 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
790 ActivityPub\Processor::updateItem($object_data);
791 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
792 ActivityPub\Processor::updatePerson($object_data);
793 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
794 // Unhandled Peertube activity
795 Queue::remove($object_data);
802 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
803 ActivityPub\Processor::deleteItem($object_data);
804 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
805 ActivityPub\Processor::deletePerson($object_data);
806 } elseif ($object_data['object_type'] == '') {
807 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
808 Queue::remove($object_data);
815 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
816 ActivityPub\Processor::movePerson($object_data);
823 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
824 ActivityPub\Processor::blockAccount($object_data);
831 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
832 ActivityPub\Processor::ReportAccount($object_data);
839 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
840 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
841 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
842 // We don't have the object here or it is deleted. We ignore this activity.
843 Queue::remove($object_data);
850 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
851 ActivityPub\Processor::followUser($object_data);
852 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
853 $object_data['reply-to-id'] = $object_data['object_id'];
854 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
861 if ($object_data['object_type'] == 'as:Follow') {
862 if (!empty($object_data['object_actor'])) {
863 ActivityPub\Processor::acceptFollowUser($object_data);
865 Logger::notice('Unhandled "accept follow" message.', ['object_data' => $object_data]);
867 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
868 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
869 } elseif (!empty($object_data['object_id']) && empty($object_data['object_actor']) && empty($object_data['object_type'])) {
870 // Follow acceptances from gup.pe only contain the object id
871 ActivityPub\Processor::acceptFollowUser($object_data);
878 if ($object_data['object_type'] == 'as:Follow') {
879 ActivityPub\Processor::rejectFollowUser($object_data);
880 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
881 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
888 if (($object_data['object_type'] == 'as:Follow') &&
889 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
890 ActivityPub\Processor::undoFollowUser($object_data);
891 } elseif (($object_data['object_type'] == 'as:Follow') &&
892 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
893 ActivityPub\Processor::undoActivity($object_data);
894 } elseif (($object_data['object_type'] == 'as:Accept') &&
895 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
896 ActivityPub\Processor::rejectFollowUser($object_data);
897 } elseif (($object_data['object_type'] == 'as:Block') &&
898 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
899 ActivityPub\Processor::unblockAccount($object_data);
900 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
901 empty($object_data['object_object_type'])) {
902 // We cannot detect the target object. So we can ignore it.
903 Queue::remove($object_data);
904 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
905 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
906 ActivityPub\Processor::undoActivity($object_data);
907 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
908 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
909 // Unhandled Peertube activity
910 Queue::remove($object_data);
911 } elseif (in_array($object_data['object_type'], ['as:Delete'])) {
912 // We cannot undo deletions, so we just ignore this
913 Queue::remove($object_data);
914 } elseif (in_array($object_data['object_object_type'], ['as:Tombstone'])) {
915 // The object is a tombstone, we ignore any actions on it.
916 Queue::remove($object_data);
923 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
924 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
925 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
926 // We don't have the object here or it is deleted. We ignore this activity.
927 Queue::remove($object_data);
933 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
934 ActivityPub\Processor::createActivity($object_data, Activity::READ);
935 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
936 // We don't have the object here or it is deleted. We ignore this activity.
937 Queue::remove($object_data);
943 case 'litepub:EmojiReact':
944 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
945 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
946 } elseif (in_array($object_data['object_type'], ['as:Tombstone', ''])) {
947 // We don't have the object here or it is deleted. We ignore this activity.
948 Queue::remove($object_data);
955 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
962 * Stores unhandled or unknown Activities as a file
964 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
965 * @param string $type Activity type
966 * @param array $object_data Preprocessed array that is generated out of the received activity
967 * @param array $activity Array with activity data
968 * @param string $body The unprocessed body
969 * @param integer $uid User ID
970 * @param boolean $trust_source Do we trust the source?
971 * @param boolean $push Message had been pushed to our system
972 * @param array $signer The signer of the post
975 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 = [])
977 if (!DI::config()->get('debug', 'ap_log_unknown')) {
981 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
983 if (!empty($object_data['object_type'])) {
984 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
987 if (!empty($object_data['object_object_type'])) {
988 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
991 $tempfile = tempnam(System::getTempPath(), $file);
992 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));
993 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], 'object_object_type' => $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
997 * Fetch a user id from an activity array
999 * @param array $activity
1000 * @param string $actor
1002 * @return int user id
1004 public static function getBestUserForActivity(array $activity): int
1007 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
1009 $receivers = self::getReceivers($activity, $actor, [], false, false);
1010 foreach ($receivers as $receiver) {
1011 if ($receiver['type'] == self::TARGET_GLOBAL) {
1014 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
1015 $uid = $receiver['uid'];
1019 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
1021 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
1022 if (!empty($contact['uid'])) {
1023 $uid = $contact['uid'];
1030 // @TODO Missing documentation
1031 public static function getReceiverURL(array $activity): array
1035 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1036 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1037 if (empty($receiver_list)) {
1041 foreach ($receiver_list as $receiver) {
1042 if ($receiver == 'Public') {
1043 Logger::warning('Not compacted public collection found', ['activity' => $activity, 'callstack' => System::callstack(20)]);
1044 $receiver = ActivityPub::PUBLIC_COLLECTION;
1046 if ($receiver == self::PUBLIC_COLLECTION) {
1047 $receiver = ActivityPub::PUBLIC_COLLECTION;
1049 $urls[$element][] = $receiver;
1057 * Fetch the receiver list from an activity array
1059 * @param array $activity
1060 * @param string $actor
1061 * @param array $tags
1062 * @param bool $fetch_unlisted
1065 * @return array with receivers (user id)
1066 * @throws \Exception
1068 private static function getReceivers(array $activity, string $actor, array $tags, bool $fetch_unlisted, bool $push): array
1070 $reply = $receivers = $profile = [];
1072 // When it is an answer, we inherit the receivers from the parent
1073 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
1074 if (!empty($replyto)) {
1075 $reply = [$replyto];
1077 // Fix possibly wrong item URI (could be an answer to a plink uri)
1078 $fixedReplyTo = Item::getURIByLink($replyto);
1079 if (!empty($fixedReplyTo)) {
1080 $reply[] = $fixedReplyTo;
1084 // Fetch all posts that refer to the object id
1085 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
1086 if (!empty($object_id)) {
1087 $reply[] = $object_id;
1090 if (!empty($actor)) {
1091 $profile = APContact::getByURL($actor);
1092 $followers = $profile['followers'] ?? '';
1093 $is_forum = ($actor['type'] ?? '') == 'Group';
1095 Contact::updateByUrlIfNeeded($actor);
1097 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1099 Logger::info('Empty actor', ['activity' => $activity]);
1104 // We have to prevent false follower assumptions upon thread completions
1105 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1107 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1108 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1109 if (empty($receiver_list)) {
1113 foreach ($receiver_list as $receiver) {
1114 if ($receiver == self::PUBLIC_COLLECTION) {
1115 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1118 // Add receiver "-1" for unlisted posts
1119 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1120 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1123 // Fetch the receivers for the public and the followers collection
1124 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1125 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1129 // Fetching all directly addressed receivers
1130 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1131 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1132 if (!DBA::isResult($contact)) {
1136 // Check if the potential receiver is following the actor
1137 // Exception: The receiver is targetted via "to" or this is a comment
1138 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1139 $networks = Protocol::FEDERATED;
1140 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1141 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1143 // Forum posts are only accepted from forum contacts
1144 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1145 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1148 if (!DBA::exists('contact', $condition)) {
1153 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1154 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1157 $type = self::TARGET_TO;
1160 $type = self::TARGET_CC;
1163 $type = self::TARGET_BTO;
1166 $type = self::TARGET_BCC;
1170 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1175 if (!empty($reply) && (!empty($receivers[0]) || !empty($receivers[-1]))) {
1176 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1177 while ($parent = Post::fetch($parents)) {
1178 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1180 DBA::close($parents);
1183 self::switchContacts($receivers, $actor);
1185 // "birdsitelive" is a service that mirrors tweets into the fediverse
1186 // These posts can be fetched without authentication, but are not marked as public
1187 // We treat them as unlisted posts to be able to handle them.
1188 if (empty($receivers) && $fetch_unlisted && Contact::isPlatform($actor, 'birdsitelive')) {
1189 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1190 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1191 Logger::notice('Post from "birdsitelive" is set to "unlisted"', ['id' => JsonLD::fetchElement($activity, '@id')]);
1192 } elseif (empty($receivers)) {
1193 Logger::notice('Post has got no receivers', ['fetch_unlisted' => $fetch_unlisted, 'actor' => $actor, 'id' => JsonLD::fetchElement($activity, '@id'), 'type' => JsonLD::fetchElement($activity, '@type')]);
1200 * Fetch the receiver list of a given actor
1202 * @param string $actor
1203 * @param array $tags
1204 * @param array $receivers
1205 * @param integer $target_type
1206 * @param array $profile
1208 * @return array with receivers (user id)
1209 * @throws \Exception
1211 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1213 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1214 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1216 if (!empty($profile['uri-id'])) {
1217 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1218 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1219 while ($contact = DBA::fetch($contacts)) {
1220 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1221 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1224 DBA::close($contacts);
1226 // This part will only be called while post update 1426 wasn't finished
1227 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1228 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1229 while ($contact = DBA::fetch($contacts)) {
1230 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1231 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1234 DBA::close($contacts);
1236 // The queries are split because of performance issues
1237 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1238 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1239 while ($contact = DBA::fetch($contacts)) {
1240 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1241 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1244 DBA::close($contacts);
1250 * Tests if the contact is a valid receiver for this actor
1252 * @param array $contact
1253 * @param array $tags
1255 * @return bool with receivers (user id)
1256 * @throws \Exception
1258 private static function isValidReceiverForActor(array $contact, array $tags): bool
1260 // Are we following the contact? Then this is a valid receiver
1261 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1265 // When the possible receiver isn't a community, then it is no valid receiver
1266 $owner = User::getOwnerDataById($contact['uid']);
1267 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1271 // Is the community account tagged?
1272 foreach ($tags as $tag) {
1273 if ($tag['type'] != 'Mention') {
1277 if (Strings::compareLink($tag['href'], $owner['url'])) {
1286 * Switches existing contacts to ActivityPub
1288 * @param integer $cid Contact ID
1289 * @param integer $uid User ID
1290 * @param string $url Profile URL
1292 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1293 * @throws \ImagickException
1295 public static function switchContact(int $cid, int $uid, string $url)
1297 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1298 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1302 if (Contact::updateFromProbe($cid)) {
1303 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1306 // Send a new follow request to be sure that the connection still exists
1307 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1308 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1309 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1314 * @TODO Fix documentation and type-hints
1319 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1320 * @throws \ImagickException
1322 private static function switchContacts($receivers, $actor)
1324 if (empty($actor)) {
1328 foreach ($receivers as $receiver) {
1329 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1330 if (DBA::isResult($contact)) {
1331 self::switchContact($contact['id'], $receiver['uid'], $actor);
1334 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1335 if (DBA::isResult($contact)) {
1336 self::switchContact($contact['id'], $receiver['uid'], $actor);
1342 * @TODO Fix documentation and type-hints
1344 * @param $object_data
1345 * @param array $activity
1349 private static function addActivityFields($object_data, array $activity)
1351 if (!empty($activity['published']) && empty($object_data['published'])) {
1352 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1355 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1356 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1359 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1360 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1362 if (!empty($object_data['object_id'])) {
1363 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1364 $objectId = Item::getURIByLink($object_data['object_id']);
1365 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1366 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1367 $object_data['object_id'] = $objectId;
1371 return $object_data;
1375 * Fetches the object data from external resources if needed
1377 * @param string $object_id Object ID of the provided object
1378 * @param array $object The provided object array
1379 * @param boolean $trust_source Do we trust the provided object?
1380 * @param integer $uid User ID for the signature that we use to fetch data
1382 * @return array|false with trusted and valid object data
1383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1384 * @throws \ImagickException
1386 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1388 // By fetching the type we check if the object is complete.
1389 $type = JsonLD::fetchElement($object, '@type');
1391 if (!$trust_source || empty($type)) {
1392 $data = Processor::fetchCachedActivity($object_id, $uid);
1393 if (!empty($data)) {
1394 $object = JsonLD::compact($data);
1395 Logger::info('Fetched content for ' . $object_id);
1397 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1399 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1400 if (!DBA::isResult($item)) {
1401 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1404 Logger::info('Using already stored item for url ' . $object_id);
1405 $data = ActivityPub\Transmitter::createNote($item);
1406 $object = JsonLD::compact($data);
1409 $id = JsonLD::fetchElement($object, '@id');
1411 Logger::info('Empty id');
1415 if ($id != $object_id) {
1416 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1420 Logger::info('Using original object for url ' . $object_id);
1423 $type = JsonLD::fetchElement($object, '@type');
1425 Logger::info('Empty type');
1429 // Lemmy is resharing "create" activities instead of content
1430 // We fetch the content from the activity.
1431 if (in_array($type, ['as:Create'])) {
1432 $object = $object['as:object'];
1433 $type = JsonLD::fetchElement($object, '@type');
1435 Logger::info('Empty type');
1438 $object_data = self::processObject($object);
1441 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1442 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1443 $object_data = self::processObject($object);
1445 if (!empty($data)) {
1446 $object_data['raw-object'] = json_encode($data);
1448 return $object_data;
1451 Logger::info('Unhandled object type: ' . $type);
1456 * Converts the language element (Used by Peertube)
1458 * @param array $languages
1459 * @return array Languages
1461 public static function processLanguages(array $languages): array
1463 if (empty($languages)) {
1467 $language_list = [];
1469 foreach ($languages as $language) {
1470 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1471 $language_list[$language['_:identifier']] = $language['as:name'];
1474 return $language_list;
1478 * Convert tags from JSON-LD format into a simplified format
1480 * @param array $tags Tags in JSON-LD format
1482 * @return array with tags in a simplified format
1484 public static function processTags(array $tags): array
1488 foreach ($tags as $tag) {
1493 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type') ?? ''),
1494 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1495 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1497 if (empty($element['type'])) {
1501 if (empty($element['href'])) {
1502 $element['href'] = $element['name'];
1505 $taglist[] = $element;
1511 * Convert emojis from JSON-LD format into a simplified format
1513 * @param array $emojis
1514 * @return array with emojis in a simplified format
1516 private static function processEmojis(array $emojis): array
1520 foreach ($emojis as $emoji) {
1521 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1525 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1526 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1529 $emojilist[] = $element;
1536 * Convert attachments from JSON-LD format into a simplified format
1538 * @param array $attachments Attachments in JSON-LD format
1540 * @return array Attachments in a simplified format
1542 private static function processAttachments(array $attachments): array
1546 // Removes empty values
1547 $attachments = array_filter($attachments);
1549 foreach ($attachments as $attachment) {
1550 switch (JsonLD::fetchElement($attachment, '@type')) {
1555 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1556 foreach ($urls as $url) {
1557 // Single scalar URL case
1558 if (is_string($url)) {
1563 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1564 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1565 if (Strings::startsWith($mediaType, 'image')) {
1574 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1575 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1577 'image' => $pageImage,
1581 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1582 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1583 $imagePreviewUrl = null;
1585 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1586 $imageVariants = [];
1587 $previewVariants = [];
1588 foreach ($urls as $url) {
1589 // Scalar URL, no discrimination possible
1590 if (is_string($url)) {
1591 $imageFullUrl = $url;
1595 // Not sure what to do with a different Link media type than the base Image, we skip
1596 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1600 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1602 // Default URL choice if no discriminating width is provided
1603 $imageFullUrl = $href ?? $imageFullUrl;
1605 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1607 if ($href && $width) {
1608 $imageVariants[$width] = $href;
1609 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1610 $previewVariants[abs(632 - $width)] = $href;
1614 if ($imageVariants) {
1615 // Taking the maximum size image
1616 ksort($imageVariants);
1617 $imageFullUrl = array_pop($imageVariants);
1619 // Taking the minimum number distance to the target distance
1620 ksort($previewVariants);
1621 $imagePreviewUrl = array_shift($previewVariants);
1624 unset($imageVariants);
1625 unset($previewVariants);
1629 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1630 'mediaType' => $mediaType,
1631 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1632 'url' => $imageFullUrl,
1633 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1638 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1639 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1640 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1641 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id') ?? JsonLD::fetchElement($attachment, 'as:href', '@id'),
1642 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1643 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1644 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1653 * Convert questions from JSON-LD format into a simplified format
1655 * @param array $object
1657 * @return array Questions in a simplified format
1659 private static function processQuestion(array $object): array
1663 if (!empty($object['as:oneOf'])) {
1664 $question['multiple'] = false;
1665 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1666 } elseif (!empty($object['as:anyOf'])) {
1667 $question['multiple'] = true;
1668 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1673 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1674 if (!empty($closed)) {
1675 $question['end-time'] = $closed;
1677 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1680 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1681 $question['options'] = [];
1685 foreach ($options as $option) {
1686 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1690 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1692 if (empty($option['as:replies'])) {
1696 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1698 $question['options'][] = ['name' => $name, 'replies' => $replies];
1700 $voters += (int)$replies;
1703 // For single choice question we can count the number of voters if not provided (like with Misskey)
1704 if (empty($question['voters']) && !$question['multiple']) {
1705 $question['voters'] = $voters;
1712 * Fetch the original source or content with the "language" Markdown or HTML
1714 * @param array $object
1715 * @param array $object_data
1717 * @return array Object data (?)
1718 * @throws \Exception
1720 private static function getSource(array $object, array $object_data): array
1722 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1723 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1724 if (!empty($object_data['source'])) {
1725 return $object_data;
1728 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1729 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1730 if (!empty($object_data['source'])) {
1731 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1732 return $object_data;
1735 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1736 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1737 if (!empty($object_data['source'])) {
1738 $object_data['source'] = HTML::toBBCode($object_data['source']);
1739 return $object_data;
1742 return $object_data;
1746 * Extracts a potential alternate URL from a list of additional URL elements
1748 * @param array $urls
1751 private static function extractAlternateUrl(array $urls): string
1754 foreach ($urls as $key => $url) {
1755 // Not a list but a single URL element
1756 if (!is_numeric($key)) {
1760 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1764 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1769 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1770 if (empty($mediatype)) {
1774 if ($mediatype == 'text/html') {
1775 $alternateUrl = $href;
1779 return $alternateUrl;
1783 * Check if the "as:url" element is an array with multiple links
1784 * This is the case with audio and video posts.
1785 * Then the links are added as attachments
1787 * @param array $urls The object URL list
1788 * @return array an array of attachments
1790 private static function processAttachmentUrls(array $urls): array
1793 foreach ($urls as $key => $url) {
1794 // Not a list but a single URL element
1795 if (!is_numeric($key)) {
1799 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1803 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1808 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1809 if (empty($mediatype)) {
1813 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1815 if ($filetype == 'audio') {
1816 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1817 } elseif ($filetype == 'video') {
1818 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1819 // PeerTube audio-only track
1820 if ($height === 0) {
1824 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1825 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1826 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1827 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1829 // For Torrent links we always store the highest resolution
1830 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1834 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1835 } elseif ($mediatype == 'application/x-mpegURL') {
1836 // PeerTube exception, actual video link is in the tags of this URL element
1837 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1841 return array_values($attachments);
1845 * Fetches data from the object part of an activity
1847 * @param array $object
1849 * @return array|bool Object data or FALSE if $object does not contain @id element
1850 * @throws \Exception
1852 private static function processObject(array $object)
1854 if (!JsonLD::fetchElement($object, '@id')) {
1858 $object_data = self::getObjectDataFromActivity($object);
1860 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true, false);
1861 $receivers = $reception_types = [];
1862 foreach ($receiverdata as $key => $data) {
1863 $receivers[$key] = $data['uid'];
1864 $reception_types[$data['uid']] = $data['type'] ?? 0;
1867 $object_data['receiver_urls'] = self::getReceiverURL($object);
1868 $object_data['receiver'] = $receivers;
1869 $object_data['reception_type'] = $reception_types;
1871 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1872 unset($object_data['receiver'][-1]);
1873 unset($object_data['reception_type'][-1]);
1875 return $object_data;
1879 * Create an object data array from a given activity
1881 * @param array $object
1883 * @return array Object data
1885 public static function getObjectDataFromActivity(array $object): array
1888 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1889 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1890 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1892 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1893 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1894 $object_data['reply-to-id'] = $object_data['id'];
1896 // On activities the "reply to" is the id of the object it refers to
1897 if (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce']))) {
1898 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1899 if (!empty($object_id)) {
1900 $object_data['reply-to-id'] = $object_id;
1904 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1905 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1906 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1907 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1908 $object_data['reply-to-id'] = $replyToId;
1912 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1913 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1915 if (empty($object_data['updated'])) {
1916 $object_data['updated'] = $object_data['published'];
1919 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1920 $object_data['published'] = $object_data['updated'];
1923 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1924 if (empty($actor)) {
1925 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1928 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1929 $location = JsonLD::fetchElement($location, 'location', '@value');
1931 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1932 // down to HTML and then finally format to plaintext.
1933 $location = Markdown::convert($location);
1934 $location = BBCode::toPlaintext($location);
1937 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1938 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1939 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1940 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1941 $object_data['actor'] = $object_data['author'] = $actor;
1942 $element = JsonLD::fetchElement($object, 'as:context', '@id');
1943 $object_data['context'] = $element != './' ? $element : null;
1944 $element = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1945 $object_data['conversation'] = $element != './' ? $element : null;
1946 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1947 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1948 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1949 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1950 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1951 $object_data = self::getSource($object, $object_data);
1952 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1953 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1954 $object_data['location'] = $location;
1955 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1956 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1957 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1958 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1959 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1960 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1961 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1962 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1963 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1964 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1965 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1967 // Special treatment for Hubzilla links
1968 if (is_array($object_data['alternate-url'])) {
1969 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1971 if (!is_string($object_data['alternate-url'])) {
1972 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1976 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1977 $object_data['alternate-url'] = null;
1980 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1981 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1982 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1985 // Support for quoted posts (Pleroma, Fedibird and Misskey)
1986 $object_data['quote-url'] = JsonLD::fetchElement($object, 'as:quoteUrl', '@value');
1987 if (empty($object_data['quote-url'])) {
1988 $object_data['quote-url'] = JsonLD::fetchElement($object, 'fedibird:quoteUri', '@value');
1990 if (empty($object_data['quote-url'])) {
1991 $object_data['quote-url'] = JsonLD::fetchElement($object, 'misskey:_misskey_quote', '@value');
1994 // Misskey adds some data to the standard "content" value for quoted posts for backwards compatibility.
1995 // Their own "_misskey_content" value does then contain the content without this extra data.
1996 if (!empty($object_data['quote-url'])) {
1997 $misskey_content = JsonLD::fetchElement($object, 'misskey:_misskey_content', '@value');
1998 if (!empty($misskey_content)) {
1999 $object_data['content'] = $misskey_content;
2003 // For page types we expect that the alternate url posts to some page.
2004 // So we add this to the attachments if it differs from the id.
2005 // Currently only Lemmy is using the page type.
2006 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
2007 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
2008 $object_data['alternate-url'] = null;
2011 if ($object_data['object_type'] == 'as:Question') {
2012 $object_data['question'] = self::processQuestion($object);
2015 return $object_data;
2019 * Add an object id to the list of arrived activities
2025 private static function addArrivedId(string $id)
2027 DBA::delete('arrived-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
2028 DBA::insert('arrived-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE);
2032 * Checks if the given object already arrived before
2038 private static function hasArrived(string $id): bool
2040 return DBA::exists('arrived-activity', ['object-id' => $id]);