3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
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'];
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_ANNOUCE = 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::warning('Invalid HTTP signature, message will be discarded.', ['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]);
134 $signer = [$http_signer];
136 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
138 if (LDSignature::isSigned($activity)) {
139 $ld_signer = LDSignature::getSigner($activity);
140 if (empty($ld_signer)) {
141 Logger::info('Invalid JSON-LD signature from ' . $actor);
142 } elseif ($ld_signer != $http_signer) {
143 $signer[] = $ld_signer;
145 if (!empty($ld_signer && ($actor == $http_signer))) {
146 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
147 $trust_source = true;
148 } elseif (!empty($ld_signer)) {
149 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
150 $trust_source = true;
151 } elseif ($actor == $http_signer) {
152 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
153 $trust_source = true;
155 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
156 $trust_source = false;
158 } elseif ($actor == $http_signer) {
159 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
160 $trust_source = true;
162 Logger::info('No JSON-LD signature, different actor.');
163 $trust_source = false;
166 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
170 * Process incoming posts from relays
172 * @param array $activity
173 * @param string $actor
176 private static function processRelayPost(array $activity, string $actor)
178 $type = JsonLD::fetchElement($activity, '@type');
180 Logger::notice('Empty type', ['activity' => $activity, 'actor' => $actor]);
184 $object_type = JsonLD::fetchElement($activity, 'as:object', '@type') ?? '';
186 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
187 if (empty($object_id)) {
188 Logger::notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]);
192 $handle = ($type == 'as:Announce');
194 if (!$handle && in_array($type, ['as:Create', 'as:Update'])) {
195 $handle = in_array($object_type, self::CONTENT_TYPES);
199 $trust_source = false;
200 $object_data = self::prepareObjectData($activity, 0, false, $trust_source);
202 if (!$trust_source) {
203 Logger::notice('Activity trust could not be achieved.', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
207 if (empty($object_data)) {
208 Logger::notice('No object data found', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
212 if (self::routeActivities($object_data, $type, true)) {
213 Logger::debug('Handled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]);
215 Logger::info('Unhandled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
220 $contact = Contact::getByURL($actor);
221 if (empty($contact)) {
222 Logger::info('Relay contact not found', ['actor' => $actor]);
226 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
227 Logger::notice('Relay is no sharer', ['actor' => $actor]);
231 Logger::debug('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
233 $item_id = Item::searchByLink($object_id);
235 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
239 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
241 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
247 * Fetches the object type for a given object id
249 * @param array $activity
250 * @param string $object_id Object ID of the the provided object
251 * @param integer $uid User ID
253 * @return string with object type or NULL
254 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
255 * @throws \ImagickException
257 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
259 if (!empty($activity['as:object'])) {
260 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
261 if (!empty($object_type)) {
266 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
267 // We just assume "note" since it doesn't make a difference for the further processing
271 $profile = APContact::getByURL($object_id);
272 if (!empty($profile['type'])) {
273 APContact::unmarkForArchival($profile);
274 return 'as:' . $profile['type'];
277 $data = Processor::fetchCachedActivity($object_id, $uid);
279 $object = JsonLD::compact($data);
280 $type = JsonLD::fetchElement($object, '@type');
290 * Prepare the object array
292 * @param array $activity Array with activity data
293 * @param integer $uid User ID
294 * @param boolean $push Message had been pushed to our system
295 * @param boolean $trust_source Do we trust the source?
297 * @return array with object data
298 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
299 * @throws \ImagickException
301 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
303 $id = JsonLD::fetchElement($activity, '@id');
304 $type = JsonLD::fetchElement($activity, '@type');
305 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
307 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
308 $fetch_id = $object_id;
313 if (!empty($activity['as:object'])) {
314 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
317 if (!empty($id) && !$trust_source) {
318 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
320 $fetched_activity = Processor::fetchCachedActivity($fetch_id, $fetch_uid);
321 if (!empty($fetched_activity)) {
322 $object = JsonLD::compact($fetched_activity);
324 $fetched_id = JsonLD::fetchElement($object, '@id');
325 $fetched_type = JsonLD::fetchElement($object, '@type');
327 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
328 Logger::info('Activity had been fetched successfully', ['id' => $id]);
329 $trust_source = true;
331 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
332 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
333 $trust_source = true;
334 unset($object['@context']);
335 $activity['as:object'] = $object;
337 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
340 Logger::info('Activity could not been fetched', ['id' => $id]);
344 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
346 Logger::info('Empty actor', ['activity' => $activity]);
350 $type = JsonLD::fetchElement($activity, '@type');
352 // Fetch all receivers from to, cc, bto and bcc
353 $receiverdata = self::getReceivers($activity, $actor);
354 $receivers = $reception_types = [];
355 foreach ($receiverdata as $key => $data) {
356 $receivers[$key] = $data['uid'];
357 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
360 $urls = self::getReceiverURL($activity);
362 // When it is a delivery to a personal inbox we add that user to the receivers
364 $additional = [$uid => $uid];
365 $receivers = array_replace($receivers, $additional);
366 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]))) {
367 $reception_types[$uid] = self::TARGET_BCC;
368 $owner = User::getOwnerDataById($uid);
369 if (!empty($owner['url'])) {
370 $urls['as:bcc'][] = $owner['url'];
375 // We possibly need some user to fetch private content,
376 // so we fetch one out of the receivers if no uid is provided.
377 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
379 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
380 if (empty($object_id)) {
381 Logger::info('No object found');
385 if (!is_string($object_id)) {
386 Logger::info('Invalid object id', ['object' => $object_id]);
390 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
392 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
393 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
394 $data = Processor::fetchCachedActivity($object_id, $fetch_uid);
396 $type = $object_type;
397 $activity = JsonLD::compact($data);
399 // Some variables need to be refetched since the activity changed
400 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
401 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
402 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
406 // Any activities on account types must not be altered
407 if (in_array($object_type, self::ACCOUNT_TYPES)) {
409 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
410 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
411 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
412 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
413 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
414 $object_data['push'] = $push;
415 if (!$trust_source && ($type == 'as:Delete')) {
416 $apcontact = APContact::getByURL($object_data['object_id'], true);
417 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
419 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
420 // Fetch the content only on activities where this matters
421 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
422 // Always fetch on "Announce"
423 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
424 if (empty($object_data)) {
425 Logger::info("Object data couldn't be processed");
429 $object_data['object_id'] = $object_id;
431 if ($type == 'as:Announce') {
432 $object_data['push'] = false;
434 $object_data['push'] = $push;
437 // Test if it is an answer to a mail
438 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
439 $object_data['directmessage'] = true;
441 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
443 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
444 // Create a mostly empty array out of the activity data (instead of the object).
445 // This way we later don't have to check for the existence of each individual array element.
446 $object_data = self::processObject($activity);
447 $object_data['name'] = $type;
448 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
449 $object_data['object_id'] = $object_id;
450 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
451 $object_data['push'] = $push;
452 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
454 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
455 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
456 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
457 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
458 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
459 $object_data['push'] = $push;
462 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
463 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
464 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
465 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
466 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
467 $object_data['push'] = $push;
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 = self::addActivityFields($object_data, $activity);
484 if (empty($object_data['object_type'])) {
485 $object_data['object_type'] = $object_type;
488 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
489 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
490 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
494 $object_data['type'] = $type;
495 $object_data['actor'] = $actor;
496 $object_data['item_receiver'] = $receivers;
497 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
498 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
500 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
501 // $author = $object_data['author'] ?? $actor;
502 // if (!empty($author) && !empty($object_data['id'])) {
503 // $author_host = parse_url($author, PHP_URL_HOST);
504 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
505 // if ($author_host == $id_host) {
506 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
508 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
509 // $trust_source = false;
513 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
519 * Fetches the first user id from the receiver array
521 * @param array $receivers Array with receivers
522 * @return integer user id;
524 public static function getFirstUserFromReceivers(array $receivers): int
526 foreach ($receivers as $receiver) {
527 if (!empty($receiver)) {
535 * Processes the activity object
537 * @param array $activity Array with activity data
538 * @param string $body The unprocessed body
539 * @param int|null $uid User ID
540 * @param boolean $trust_source Do we trust the source?
541 * @param boolean $push Message had been pushed to our system
542 * @param array $signer The signer of the post
546 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
547 * @throws \ImagickException
549 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
551 $type = JsonLD::fetchElement($activity, '@type');
553 Logger::info('Empty type', ['activity' => $activity]);
557 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
558 Logger::info('Empty object', ['activity' => $activity]);
562 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
564 Logger::info('Empty actor', ['activity' => $activity]);
568 if (is_array($activity['as:object'])) {
569 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
574 // Test the provided signatures against the actor and "attributedTo"
576 if (!empty($attributed_to) && !empty($actor)) {
577 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
579 $trust_source = in_array($actor, $signer);
583 // $trust_source is called by reference and is set to true if the content was retrieved successfully
584 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
585 if (empty($object_data)) {
586 Logger::info('No object data found', ['activity' => $activity]);
590 // Lemmy is announcing activities.
591 // We are changing the announces into regular activities.
592 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
593 $type = $object_data['type'];
596 if (!empty($body) && empty($object_data['raw'])) {
597 $object_data['raw'] = $body;
600 // Internal flag for thread completion. See Processor.php
601 if (!empty($activity['thread-completion'])) {
602 $object_data['thread-completion'] = $activity['thread-completion'];
605 if (!empty($activity['completion-mode'])) {
606 $object_data['completion-mode'] = $activity['completion-mode'];
609 if (!empty($activity['thread-children-type'])) {
610 $object_data['thread-children-type'] = $activity['thread-children-type'];
613 // Internal flag for posts that arrived via relay
614 if (!empty($activity['from-relay'])) {
615 $object_data['from-relay'] = $activity['from-relay'];
618 if ($type == 'as:Announce') {
619 $object_data['object_activity'] = $activity;
622 if (($type == 'as:Create') && $trust_source) {
623 if (self::hasArrived($object_data['object_id'])) {
624 Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]);
627 self::addArrivedId($object_data['object_id']);
629 if (Queue::exists($object_data['object_id'], $type)) {
630 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
635 if (DI::config()->get('system', 'decoupled_receiver') && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
636 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
639 if (!$trust_source) {
640 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
644 if (!empty($object_data['entry-id']) && DI::config()->get('system', 'decoupled_receiver') && ($push || ($completion == self::COMPLETION_RELAY))) {
645 if (Queue::isProcessable($object_data['entry-id'])) {
646 // We delay by 5 seconds to allow to accumulate all receivers
647 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
648 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
649 $wid = Worker::add(['priority' => PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
650 Queue::setWorkerId($object_data['entry-id'], $wid);
652 Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]);
657 if (!empty($activity['recursion-depth'])) {
658 $object_data['recursion-depth'] = $activity['recursion-depth'];
661 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
662 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
665 if (!self::routeActivities($object_data, $type, $push)) {
666 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
667 Queue::remove($object_data);
675 * @param array $object_data
676 * @param string $type
678 * @param bool $fetch_parents
680 * @return boolean Could the activity be routed?
682 public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true): bool
684 $activity = $object_data['object_activity'] ?? [];
688 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
689 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
690 ActivityPub\Processor::postItem($object_data, $item);
691 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
692 // Unhandled Peertube activity
693 Queue::remove($object_data);
700 if (in_array($object_data['object_type'], ['as:Event'])) {
701 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
702 ActivityPub\Processor::postItem($object_data, $item);
709 if ($object_data['object_type'] == 'as:tag') {
710 ActivityPub\Processor::addTag($object_data);
711 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
712 ActivityPub\Processor::addToFeaturedCollection($object_data);
713 } elseif ($object_data['object_type'] == '') {
714 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
715 Queue::remove($object_data);
722 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
723 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
724 $object_data['thread-completion'] = Contact::getIdForURL($actor);
725 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
727 if (!Post::exists(['uri' => $object_data['id'], 'uid' => 0])) {
728 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
733 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
734 ActivityPub\Processor::postItem($object_data, $item);
736 Logger::info('Announced id already exists', ['id' => $object_data['id']]);
737 Queue::remove($object_data);
740 if (!empty($activity)) {
741 $announce_object_data = self::processObject($activity);
742 $announce_object_data['name'] = $type;
743 $announce_object_data['author'] = $actor;
744 $announce_object_data['object_id'] = $object_data['object_id'];
745 $announce_object_data['object_type'] = $object_data['object_type'];
746 $announce_object_data['push'] = $push;
748 if (!empty($object_data['raw'])) {
749 $announce_object_data['raw'] = $object_data['raw'];
751 if (!empty($object_data['raw-object'])) {
752 $announce_object_data['raw-object'] = $object_data['raw-object'];
754 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
762 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
763 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
764 } elseif ($object_data['object_type'] == '') {
765 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
766 Queue::remove($object_data);
773 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
774 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
775 } elseif ($object_data['object_type'] == '') {
776 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
777 Queue::remove($object_data);
783 case 'as:TentativeAccept':
784 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
785 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
792 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
793 ActivityPub\Processor::updateItem($object_data);
794 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
795 ActivityPub\Processor::updatePerson($object_data);
796 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
797 // Unhandled Peertube activity
798 Queue::remove($object_data);
805 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
806 ActivityPub\Processor::deleteItem($object_data);
807 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
808 ActivityPub\Processor::deletePerson($object_data);
809 } elseif ($object_data['object_type'] == '') {
810 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
811 Queue::remove($object_data);
818 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
819 ActivityPub\Processor::blockAccount($object_data);
826 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
827 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
828 } elseif ($object_data['object_type'] == '') {
829 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
830 Queue::remove($object_data);
837 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
838 ActivityPub\Processor::followUser($object_data);
839 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
840 $object_data['reply-to-id'] = $object_data['object_id'];
841 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
848 if ($object_data['object_type'] == 'as:Follow') {
849 ActivityPub\Processor::acceptFollowUser($object_data);
850 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
851 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
858 if ($object_data['object_type'] == 'as:Follow') {
859 ActivityPub\Processor::rejectFollowUser($object_data);
860 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
861 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
868 if (($object_data['object_type'] == 'as:Follow') &&
869 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
870 ActivityPub\Processor::undoFollowUser($object_data);
871 } elseif (($object_data['object_type'] == 'as:Follow') &&
872 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
873 ActivityPub\Processor::undoActivity($object_data);
874 } elseif (($object_data['object_type'] == 'as:Accept') &&
875 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
876 ActivityPub\Processor::rejectFollowUser($object_data);
877 } elseif (($object_data['object_type'] == 'as:Block') &&
878 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
879 ActivityPub\Processor::unblockAccount($object_data);
880 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
881 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
882 ActivityPub\Processor::undoActivity($object_data);
883 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
884 empty($object_data['object_object_type'])) {
885 // We cannot detect the target object. So we can ignore it.
886 Queue::remove($object_data);
887 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
888 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
889 // Unhandled Peertube activity
890 Queue::remove($object_data);
897 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
898 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
899 } elseif ($object_data['object_type'] == '') {
900 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
901 Queue::remove($object_data);
907 case 'litepub:EmojiReact':
908 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
909 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
910 } elseif ($object_data['object_type'] == '') {
911 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
912 Queue::remove($object_data);
919 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
926 * Stores unhandled or unknown Activities as a file
928 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
929 * @param string $type Activity type
930 * @param array $object_data Preprocessed array that is generated out of the received activity
931 * @param array $activity Array with activity data
932 * @param string $body The unprocessed body
933 * @param integer $uid User ID
934 * @param boolean $trust_source Do we trust the source?
935 * @param boolean $push Message had been pushed to our system
936 * @param array $signer The signer of the post
939 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 = [])
941 if (!DI::config()->get('debug', 'ap_log_unknown')) {
945 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
947 if (!empty($object_data['object_type'])) {
948 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
951 if (!empty($object_data['object_object_type'])) {
952 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
955 $tempfile = tempnam(System::getTempPath(), $file);
956 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));
957 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
961 * Fetch a user id from an activity array
963 * @param array $activity
964 * @param string $actor
966 * @return int user id
968 public static function getBestUserForActivity(array $activity): int
971 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
973 $receivers = self::getReceivers($activity, $actor);
974 foreach ($receivers as $receiver) {
975 if ($receiver['type'] == self::TARGET_GLOBAL) {
978 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
979 $uid = $receiver['uid'];
983 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
985 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
986 if (!empty($contact['uid'])) {
987 $uid = $contact['uid'];
994 // @TODO Missing documentation
995 public static function getReceiverURL(array $activity): array
999 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1000 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1001 if (empty($receiver_list)) {
1005 foreach ($receiver_list as $receiver) {
1006 if ($receiver == self::PUBLIC_COLLECTION) {
1007 $receiver = ActivityPub::PUBLIC_COLLECTION;
1009 $urls[$element][] = $receiver;
1017 * Fetch the receiver list from an activity array
1019 * @param array $activity
1020 * @param string $actor
1021 * @param array $tags
1022 * @param boolean $fetch_unlisted
1024 * @return array with receivers (user id)
1025 * @throws \Exception
1027 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
1029 $reply = $receivers = $profile = [];
1031 // When it is an answer, we inherite the receivers from the parent
1032 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
1033 if (!empty($replyto)) {
1034 $reply = [$replyto];
1036 // Fix possibly wrong item URI (could be an answer to a plink uri)
1037 $fixedReplyTo = Item::getURIByLink($replyto);
1038 if (!empty($fixedReplyTo)) {
1039 $reply[] = $fixedReplyTo;
1043 // Fetch all posts that refer to the object id
1044 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
1045 if (!empty($object_id)) {
1046 $reply[] = $object_id;
1049 if (!empty($reply)) {
1050 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1051 while ($parent = Post::fetch($parents)) {
1052 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1054 DBA::close($parents);
1057 if (!empty($actor)) {
1058 $profile = APContact::getByURL($actor);
1059 $followers = $profile['followers'] ?? '';
1060 $is_forum = ($actor['type'] ?? '') == 'Group';
1061 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1063 Logger::info('Empty actor', ['activity' => $activity]);
1068 // We have to prevent false follower assumptions upon thread completions
1069 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1071 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1072 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1073 if (empty($receiver_list)) {
1077 foreach ($receiver_list as $receiver) {
1078 if ($receiver == self::PUBLIC_COLLECTION) {
1079 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1082 // Add receiver "-1" for unlisted posts
1083 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1084 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1087 // Fetch the receivers for the public and the followers collection
1088 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1089 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1093 // Fetching all directly addressed receivers
1094 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1095 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1096 if (!DBA::isResult($contact)) {
1100 // Check if the potential receiver is following the actor
1101 // Exception: The receiver is targetted via "to" or this is a comment
1102 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1103 $networks = Protocol::FEDERATED;
1104 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1105 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1107 // Forum posts are only accepted from forum contacts
1108 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1109 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1112 if (!DBA::exists('contact', $condition)) {
1117 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1118 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1121 $type = self::TARGET_TO;
1124 $type = self::TARGET_CC;
1127 $type = self::TARGET_BTO;
1130 $type = self::TARGET_BCC;
1134 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1139 self::switchContacts($receivers, $actor);
1145 * Fetch the receiver list of a given actor
1147 * @param string $actor
1148 * @param array $tags
1149 * @param array $receivers
1150 * @param integer $target_type
1151 * @param array $profile
1153 * @return array with receivers (user id)
1154 * @throws \Exception
1156 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1158 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1159 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1161 if (!empty($profile['uri-id'])) {
1162 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1163 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1164 while ($contact = DBA::fetch($contacts)) {
1165 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1166 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1169 DBA::close($contacts);
1171 // This part will only be called while post update 1426 wasn't finished
1172 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1173 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1174 while ($contact = DBA::fetch($contacts)) {
1175 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1176 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1179 DBA::close($contacts);
1181 // The queries are split because of performance issues
1182 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1183 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1184 while ($contact = DBA::fetch($contacts)) {
1185 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1186 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1189 DBA::close($contacts);
1195 * Tests if the contact is a valid receiver for this actor
1197 * @param array $contact
1198 * @param array $tags
1200 * @return bool with receivers (user id)
1201 * @throws \Exception
1203 private static function isValidReceiverForActor(array $contact, array $tags): bool
1205 // Are we following the contact? Then this is a valid receiver
1206 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1210 // When the possible receiver isn't a community, then it is no valid receiver
1211 $owner = User::getOwnerDataById($contact['uid']);
1212 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1216 // Is the community account tagged?
1217 foreach ($tags as $tag) {
1218 if ($tag['type'] != 'Mention') {
1222 if (Strings::compareLink($tag['href'], $owner['url'])) {
1231 * Switches existing contacts to ActivityPub
1233 * @param integer $cid Contact ID
1234 * @param integer $uid User ID
1235 * @param string $url Profile URL
1237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1238 * @throws \ImagickException
1240 public static function switchContact(int $cid, int $uid, string $url)
1242 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1243 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1247 if (Contact::updateFromProbe($cid)) {
1248 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1251 // Send a new follow request to be sure that the connection still exists
1252 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1253 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1254 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1259 * @TODO Fix documentation and type-hints
1264 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1265 * @throws \ImagickException
1267 private static function switchContacts($receivers, $actor)
1269 if (empty($actor)) {
1273 foreach ($receivers as $receiver) {
1274 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1275 if (DBA::isResult($contact)) {
1276 self::switchContact($contact['id'], $receiver['uid'], $actor);
1279 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1280 if (DBA::isResult($contact)) {
1281 self::switchContact($contact['id'], $receiver['uid'], $actor);
1287 * @TODO Fix documentation and type-hints
1289 * @param $object_data
1290 * @param array $activity
1294 private static function addActivityFields($object_data, array $activity)
1296 if (!empty($activity['published']) && empty($object_data['published'])) {
1297 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1300 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1301 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1304 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1305 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1307 if (!empty($object_data['object_id'])) {
1308 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1309 $objectId = Item::getURIByLink($object_data['object_id']);
1310 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1311 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1312 $object_data['object_id'] = $objectId;
1316 return $object_data;
1320 * Fetches the object data from external ressources if needed
1322 * @param string $object_id Object ID of the the provided object
1323 * @param array $object The provided object array
1324 * @param boolean $trust_source Do we trust the provided object?
1325 * @param integer $uid User ID for the signature that we use to fetch data
1327 * @return array|false with trusted and valid object data
1328 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1329 * @throws \ImagickException
1331 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1333 // By fetching the type we check if the object is complete.
1334 $type = JsonLD::fetchElement($object, '@type');
1336 if (!$trust_source || empty($type)) {
1337 $data = Processor::fetchCachedActivity($object_id, $uid);
1338 if (!empty($data)) {
1339 $object = JsonLD::compact($data);
1340 Logger::info('Fetched content for ' . $object_id);
1342 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1344 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1345 if (!DBA::isResult($item)) {
1346 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1349 Logger::info('Using already stored item for url ' . $object_id);
1350 $data = ActivityPub\Transmitter::createNote($item);
1351 $object = JsonLD::compact($data);
1354 $id = JsonLD::fetchElement($object, '@id');
1356 Logger::info('Empty id');
1360 if ($id != $object_id) {
1361 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1365 Logger::info('Using original object for url ' . $object_id);
1368 $type = JsonLD::fetchElement($object, '@type');
1370 Logger::info('Empty type');
1374 // Lemmy is resharing "create" activities instead of content
1375 // We fetch the content from the activity.
1376 if (in_array($type, ['as:Create'])) {
1377 $object = $object['as:object'];
1378 $type = JsonLD::fetchElement($object, '@type');
1380 Logger::info('Empty type');
1383 $object_data = self::processObject($object);
1386 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1387 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1388 $object_data = self::processObject($object);
1390 if (!empty($data)) {
1391 $object_data['raw-object'] = json_encode($data);
1393 return $object_data;
1396 if ($type == 'as:Announce') {
1397 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1398 if (empty($object_id) || !is_string($object_id)) {
1401 return self::fetchObject($object_id, [], false, $uid);
1404 Logger::info('Unhandled object type: ' . $type);
1409 * Converts the language element (Used by Peertube)
1411 * @param array $languages
1412 * @return array Languages
1414 public static function processLanguages(array $languages): array
1416 if (empty($languages)) {
1420 $language_list = [];
1422 foreach ($languages as $language) {
1423 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1424 $language_list[$language['_:identifier']] = $language['as:name'];
1427 return $language_list;
1431 * Convert tags from JSON-LD format into a simplified format
1433 * @param array $tags Tags in JSON-LD format
1435 * @return array with tags in a simplified format
1437 public static function processTags(array $tags): array
1441 foreach ($tags as $tag) {
1446 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1447 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1448 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1450 if (empty($element['type'])) {
1454 if (empty($element['href'])) {
1455 $element['href'] = $element['name'];
1458 $taglist[] = $element;
1464 * Convert emojis from JSON-LD format into a simplified format
1466 * @param array $emojis
1467 * @return array with emojis in a simplified format
1469 private static function processEmojis(array $emojis): array
1473 foreach ($emojis as $emoji) {
1474 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1478 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1479 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1482 $emojilist[] = $element;
1489 * Convert attachments from JSON-LD format into a simplified format
1491 * @param array $attachments Attachments in JSON-LD format
1493 * @return array Attachments in a simplified format
1495 private static function processAttachments(array $attachments): array
1499 // Removes empty values
1500 $attachments = array_filter($attachments);
1502 foreach ($attachments as $attachment) {
1503 switch (JsonLD::fetchElement($attachment, '@type')) {
1508 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1509 foreach ($urls as $url) {
1510 // Single scalar URL case
1511 if (is_string($url)) {
1516 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1517 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1518 if (Strings::startsWith($mediaType, 'image')) {
1527 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1528 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1530 'image' => $pageImage,
1534 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1535 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1536 $imagePreviewUrl = null;
1538 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1539 $imageVariants = [];
1540 $previewVariants = [];
1541 foreach ($urls as $url) {
1542 // Scalar URL, no discrimination possible
1543 if (is_string($url)) {
1544 $imageFullUrl = $url;
1548 // Not sure what to do with a different Link media type than the base Image, we skip
1549 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1553 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1555 // Default URL choice if no discriminating width is provided
1556 $imageFullUrl = $href ?? $imageFullUrl;
1558 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1560 if ($href && $width) {
1561 $imageVariants[$width] = $href;
1562 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1563 $previewVariants[abs(632 - $width)] = $href;
1567 if ($imageVariants) {
1568 // Taking the maximum size image
1569 ksort($imageVariants);
1570 $imageFullUrl = array_pop($imageVariants);
1572 // Taking the minimum number distance to the target distance
1573 ksort($previewVariants);
1574 $imagePreviewUrl = array_shift($previewVariants);
1577 unset($imageVariants);
1578 unset($previewVariants);
1582 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1583 'mediaType' => $mediaType,
1584 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1585 'url' => $imageFullUrl,
1586 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1591 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1592 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1593 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1594 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1595 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1596 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1597 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1606 * Convert questions from JSON-LD format into a simplified format
1608 * @param array $object
1610 * @return array Questions in a simplified format
1612 private static function processQuestion(array $object): array
1616 if (!empty($object['as:oneOf'])) {
1617 $question['multiple'] = false;
1618 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1619 } elseif (!empty($object['as:anyOf'])) {
1620 $question['multiple'] = true;
1621 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1626 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1627 if (!empty($closed)) {
1628 $question['end-time'] = $closed;
1630 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1633 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1634 $question['options'] = [];
1638 foreach ($options as $option) {
1639 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1643 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1645 if (empty($option['as:replies'])) {
1649 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1651 $question['options'][] = ['name' => $name, 'replies' => $replies];
1653 $voters += (int)$replies;
1656 // For single choice question we can count the number of voters if not provided (like with Misskey)
1657 if (empty($question['voters']) && !$question['multiple']) {
1658 $question['voters'] = $voters;
1665 * Fetch the original source or content with the "language" Markdown or HTML
1667 * @param array $object
1668 * @param array $object_data
1670 * @return array Object data (?)
1671 * @throws \Exception
1673 private static function getSource(array $object, array $object_data): array
1675 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1676 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1677 if (!empty($object_data['source'])) {
1678 return $object_data;
1681 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1682 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1683 if (!empty($object_data['source'])) {
1684 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1685 return $object_data;
1688 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1689 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1690 if (!empty($object_data['source'])) {
1691 $object_data['source'] = HTML::toBBCode($object_data['source']);
1692 return $object_data;
1695 return $object_data;
1699 * Extracts a potential alternate URL from a list of additional URL elements
1701 * @param array $urls
1704 private static function extractAlternateUrl(array $urls): string
1707 foreach ($urls as $key => $url) {
1708 // Not a list but a single URL element
1709 if (!is_numeric($key)) {
1713 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1717 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1722 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1723 if (empty($mediatype)) {
1727 if ($mediatype == 'text/html') {
1728 $alternateUrl = $href;
1732 return $alternateUrl;
1736 * Check if the "as:url" element is an array with multiple links
1737 * This is the case with audio and video posts.
1738 * Then the links are added as attachments
1740 * @param array $urls The object URL list
1741 * @return array an array of attachments
1743 private static function processAttachmentUrls(array $urls): array
1746 foreach ($urls as $key => $url) {
1747 // Not a list but a single URL element
1748 if (!is_numeric($key)) {
1752 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1756 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1761 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1762 if (empty($mediatype)) {
1766 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1768 if ($filetype == 'audio') {
1769 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1770 } elseif ($filetype == 'video') {
1771 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1772 // PeerTube audio-only track
1773 if ($height === 0) {
1777 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1778 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1779 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1780 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1782 // For Torrent links we always store the highest resolution
1783 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1787 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1788 } elseif ($mediatype == 'application/x-mpegURL') {
1789 // PeerTube exception, actual video link is in the tags of this URL element
1790 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1794 return array_values($attachments);
1798 * Fetches data from the object part of an activity
1800 * @param array $object
1802 * @return array|bool Object data or FALSE if $object does not contain @id element
1803 * @throws \Exception
1805 private static function processObject(array $object)
1807 if (!JsonLD::fetchElement($object, '@id')) {
1812 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1813 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1814 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1816 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1817 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1818 $object_data['reply-to-id'] = $object_data['id'];
1820 // On activities the "reply to" is the id of the object it refers to
1821 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1822 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1823 if (!empty($object_id)) {
1824 $object_data['reply-to-id'] = $object_id;
1828 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1829 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1830 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1831 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1832 $object_data['reply-to-id'] = $replyToId;
1836 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1837 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1839 if (empty($object_data['updated'])) {
1840 $object_data['updated'] = $object_data['published'];
1843 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1844 $object_data['published'] = $object_data['updated'];
1847 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1848 if (empty($actor)) {
1849 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1852 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1853 $location = JsonLD::fetchElement($location, 'location', '@value');
1855 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1856 // down to HTML and then finally format to plaintext.
1857 $location = Markdown::convert($location);
1858 $location = BBCode::toPlaintext($location);
1861 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1862 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1863 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1864 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1865 $object_data['actor'] = $object_data['author'] = $actor;
1866 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1867 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1868 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1869 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1870 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1871 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1872 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1873 $object_data = self::getSource($object, $object_data);
1874 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1875 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1876 $object_data['location'] = $location;
1877 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1878 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1879 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1880 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1881 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1882 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1883 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1884 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1885 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1886 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1887 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1889 // Special treatment for Hubzilla links
1890 if (is_array($object_data['alternate-url'])) {
1891 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1893 if (!is_string($object_data['alternate-url'])) {
1894 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1898 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1899 $object_data['alternate-url'] = null;
1902 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1903 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1904 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1907 // For page types we expect that the alternate url posts to some page.
1908 // So we add this to the attachments if it differs from the id.
1909 // Currently only Lemmy is using the page type.
1910 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1911 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1912 $object_data['alternate-url'] = null;
1915 if ($object_data['object_type'] == 'as:Question') {
1916 $object_data['question'] = self::processQuestion($object);
1919 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1920 $receivers = $reception_types = [];
1921 foreach ($receiverdata as $key => $data) {
1922 $receivers[$key] = $data['uid'];
1923 $reception_types[$data['uid']] = $data['type'] ?? 0;
1926 $object_data['receiver_urls'] = self::getReceiverURL($object);
1927 $object_data['receiver'] = $receivers;
1928 $object_data['reception_type'] = $reception_types;
1930 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1931 unset($object_data['receiver'][-1]);
1932 unset($object_data['reception_type'][-1]);
1934 return $object_data;
1938 * Add an object id to the list of arrived activities
1944 private static function addArrivedId(string $id)
1946 DBA::delete('arrived-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
1947 DBA::insert('arrived-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE);
1951 * Checks if the given object already arrived before
1957 private static function hasArrived(string $id): bool
1959 return DBA::exists('arrived-activity', ['object-id' => $id]);