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 Logger::debug('Fetch announced activity', ['object' => $object_id]);
395 $data = Processor::fetchCachedActivity($object_id, $fetch_uid);
397 $type = $object_type;
398 $activity = JsonLD::compact($data);
400 // Some variables need to be refetched since the activity changed
401 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
402 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
403 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
407 // Any activities on account types must not be altered
408 if (in_array($object_type, self::ACCOUNT_TYPES)) {
410 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
411 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
412 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
413 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
414 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
415 $object_data['push'] = $push;
416 if (!$trust_source && ($type == 'as:Delete')) {
417 $apcontact = APContact::getByURL($object_data['object_id'], true);
418 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
420 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
421 // Fetch the content only on activities where this matters
422 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
423 // Always fetch on "Announce"
424 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
425 if (empty($object_data)) {
426 Logger::info("Object data couldn't be processed");
430 $object_data['object_id'] = $object_id;
432 if ($type == 'as:Announce') {
433 $object_data['push'] = false;
435 $object_data['push'] = $push;
438 // Test if it is an answer to a mail
439 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
440 $object_data['directmessage'] = true;
442 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
444 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
445 // Create a mostly empty array out of the activity data (instead of the object).
446 // This way we later don't have to check for the existence of each individual array element.
447 $object_data = self::processObject($activity);
448 $object_data['name'] = $type;
449 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
450 $object_data['object_id'] = $object_id;
451 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
452 $object_data['push'] = $push;
453 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
455 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
456 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
457 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
458 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
459 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
460 $object_data['push'] = $push;
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');
468 $object_data['push'] = $push;
470 // An Undo is done on the object of an object, so we need that type as well
471 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
472 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
475 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
476 $trust_source = Processor::isActivityGone($object_data['object_id']);
477 if (!$trust_source) {
478 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
483 $object_data = self::addActivityFields($object_data, $activity);
485 if (empty($object_data['object_type'])) {
486 $object_data['object_type'] = $object_type;
489 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
490 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
491 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
495 $object_data['type'] = $type;
496 $object_data['actor'] = $actor;
497 $object_data['item_receiver'] = $receivers;
498 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
499 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
501 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
502 // $author = $object_data['author'] ?? $actor;
503 // if (!empty($author) && !empty($object_data['id'])) {
504 // $author_host = parse_url($author, PHP_URL_HOST);
505 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
506 // if ($author_host == $id_host) {
507 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
509 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
510 // $trust_source = false;
514 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
520 * Fetches the first user id from the receiver array
522 * @param array $receivers Array with receivers
523 * @return integer user id;
525 public static function getFirstUserFromReceivers(array $receivers): int
527 foreach ($receivers as $receiver) {
528 if (!empty($receiver)) {
536 * Processes the activity object
538 * @param array $activity Array with activity data
539 * @param string $body The unprocessed body
540 * @param int|null $uid User ID
541 * @param boolean $trust_source Do we trust the source?
542 * @param boolean $push Message had been pushed to our system
543 * @param array $signer The signer of the post
547 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
548 * @throws \ImagickException
550 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
552 $type = JsonLD::fetchElement($activity, '@type');
554 Logger::info('Empty type', ['activity' => $activity]);
558 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
559 Logger::info('Empty object', ['activity' => $activity]);
563 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
565 Logger::info('Empty actor', ['activity' => $activity]);
569 if (is_array($activity['as:object'])) {
570 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
575 // Test the provided signatures against the actor and "attributedTo"
577 if (!empty($attributed_to) && !empty($actor)) {
578 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
580 $trust_source = in_array($actor, $signer);
584 // $trust_source is called by reference and is set to true if the content was retrieved successfully
585 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
586 if (empty($object_data)) {
587 Logger::info('No object data found', ['activity' => $activity]);
591 // Lemmy is announcing activities.
592 // We are changing the announces into regular activities.
593 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
594 Logger::debug('Change type of announce to activity', ['type' => $object_data['type']]);
595 $type = $object_data['type'];
598 if (!empty($body) && empty($object_data['raw'])) {
599 $object_data['raw'] = $body;
602 // Internal flag for thread completion. See Processor.php
603 if (!empty($activity['thread-completion'])) {
604 $object_data['thread-completion'] = $activity['thread-completion'];
607 if (!empty($activity['completion-mode'])) {
608 $object_data['completion-mode'] = $activity['completion-mode'];
611 if (!empty($activity['thread-children-type'])) {
612 $object_data['thread-children-type'] = $activity['thread-children-type'];
615 // Internal flag for posts that arrived via relay
616 if (!empty($activity['from-relay'])) {
617 $object_data['from-relay'] = $activity['from-relay'];
620 if ($type == 'as:Announce') {
621 $object_data['object_activity'] = $activity;
624 if (($type == 'as:Create') && $trust_source) {
625 if (self::hasArrived($object_data['object_id'])) {
626 Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]);
629 self::addArrivedId($object_data['object_id']);
631 if (Queue::exists($object_data['object_id'], $type)) {
632 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
637 if (DI::config()->get('system', 'decoupled_receiver') && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
638 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
641 if (!$trust_source) {
642 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
646 if (!empty($object_data['entry-id']) && DI::config()->get('system', 'decoupled_receiver') && ($push || ($completion == self::COMPLETION_RELAY))) {
647 if (Queue::isProcessable($object_data['entry-id'])) {
648 // We delay by 5 seconds to allow to accumulate all receivers
649 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
650 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
651 $wid = Worker::add(['priority' => PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
652 Queue::setWorkerId($object_data['entry-id'], $wid);
654 Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]);
659 if (!empty($activity['recursion-depth'])) {
660 $object_data['recursion-depth'] = $activity['recursion-depth'];
663 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
664 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
667 if (!self::routeActivities($object_data, $type, $push)) {
668 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
669 Queue::remove($object_data);
677 * @param array $object_data
678 * @param string $type
680 * @param bool $fetch_parents
682 * @return boolean Could the activity be routed?
684 public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true): bool
686 $activity = $object_data['object_activity'] ?? [];
690 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
691 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
692 ActivityPub\Processor::postItem($object_data, $item);
693 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
694 // Unhandled Peertube activity
695 Queue::remove($object_data);
702 if (in_array($object_data['object_type'], ['as:Event'])) {
703 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
704 ActivityPub\Processor::postItem($object_data, $item);
711 if ($object_data['object_type'] == 'as:tag') {
712 ActivityPub\Processor::addTag($object_data);
713 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
714 ActivityPub\Processor::addToFeaturedCollection($object_data);
715 } elseif ($object_data['object_type'] == '') {
716 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
717 Queue::remove($object_data);
724 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
725 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
726 $object_data['thread-completion'] = Contact::getIdForURL($actor);
727 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
729 if (!Post::exists(['uri' => $object_data['id'], 'uid' => 0])) {
730 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
732 Logger::debug('announced id was not created', ['id' => $object_data['id']]);
736 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
737 ActivityPub\Processor::postItem($object_data, $item);
738 Logger::debug('Created announced id', ['id' => $object_data['id']]);
740 Logger::info('Announced id already exists', ['id' => $object_data['id']]);
741 Queue::remove($object_data);
744 if (!empty($activity)) {
745 $announce_object_data = self::processObject($activity);
746 $announce_object_data['name'] = $type;
747 $announce_object_data['author'] = $actor;
748 $announce_object_data['object_id'] = $object_data['id'];
749 $announce_object_data['object_type'] = $object_data['object_type'];
750 $announce_object_data['push'] = $push;
751 Logger::debug('Create announce activity', ['id' => $announce_object_data['id'], 'object_data' => $announce_object_data]);
753 if (!empty($object_data['raw'])) {
754 $announce_object_data['raw'] = $object_data['raw'];
756 if (!empty($object_data['raw-object'])) {
757 $announce_object_data['raw-object'] = $object_data['raw-object'];
759 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
767 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
768 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
769 } elseif ($object_data['object_type'] == '') {
770 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
771 Queue::remove($object_data);
778 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
779 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
780 } elseif ($object_data['object_type'] == '') {
781 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
782 Queue::remove($object_data);
788 case 'as:TentativeAccept':
789 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
790 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
797 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
798 ActivityPub\Processor::updateItem($object_data);
799 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
800 ActivityPub\Processor::updatePerson($object_data);
801 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
802 // Unhandled Peertube activity
803 Queue::remove($object_data);
810 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
811 ActivityPub\Processor::deleteItem($object_data);
812 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
813 ActivityPub\Processor::deletePerson($object_data);
814 } elseif ($object_data['object_type'] == '') {
815 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
816 Queue::remove($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::CONTENT_TYPES)) {
832 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
833 } elseif ($object_data['object_type'] == '') {
834 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
835 Queue::remove($object_data);
842 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
843 ActivityPub\Processor::followUser($object_data);
844 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
845 $object_data['reply-to-id'] = $object_data['object_id'];
846 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
853 if ($object_data['object_type'] == 'as:Follow') {
854 ActivityPub\Processor::acceptFollowUser($object_data);
855 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
856 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
863 if ($object_data['object_type'] == 'as:Follow') {
864 ActivityPub\Processor::rejectFollowUser($object_data);
865 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
866 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
873 if (($object_data['object_type'] == 'as:Follow') &&
874 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
875 ActivityPub\Processor::undoFollowUser($object_data);
876 } elseif (($object_data['object_type'] == 'as:Follow') &&
877 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
878 ActivityPub\Processor::undoActivity($object_data);
879 } elseif (($object_data['object_type'] == 'as:Accept') &&
880 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
881 ActivityPub\Processor::rejectFollowUser($object_data);
882 } elseif (($object_data['object_type'] == 'as:Block') &&
883 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
884 ActivityPub\Processor::unblockAccount($object_data);
885 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
886 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
887 ActivityPub\Processor::undoActivity($object_data);
888 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
889 empty($object_data['object_object_type'])) {
890 // We cannot detect the target object. So we can ignore it.
891 Queue::remove($object_data);
892 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
893 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
894 // Unhandled Peertube activity
895 Queue::remove($object_data);
902 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
903 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
904 } elseif ($object_data['object_type'] == '') {
905 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
906 Queue::remove($object_data);
912 case 'litepub:EmojiReact':
913 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
914 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
915 } elseif ($object_data['object_type'] == '') {
916 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
917 Queue::remove($object_data);
924 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
931 * Stores unhandled or unknown Activities as a file
933 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
934 * @param string $type Activity type
935 * @param array $object_data Preprocessed array that is generated out of the received activity
936 * @param array $activity Array with activity data
937 * @param string $body The unprocessed body
938 * @param integer $uid User ID
939 * @param boolean $trust_source Do we trust the source?
940 * @param boolean $push Message had been pushed to our system
941 * @param array $signer The signer of the post
944 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 = [])
946 if (!DI::config()->get('debug', 'ap_log_unknown')) {
950 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
952 if (!empty($object_data['object_type'])) {
953 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
956 if (!empty($object_data['object_object_type'])) {
957 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
960 $tempfile = tempnam(System::getTempPath(), $file);
961 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));
962 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
966 * Fetch a user id from an activity array
968 * @param array $activity
969 * @param string $actor
971 * @return int user id
973 public static function getBestUserForActivity(array $activity): int
976 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
978 $receivers = self::getReceivers($activity, $actor);
979 foreach ($receivers as $receiver) {
980 if ($receiver['type'] == self::TARGET_GLOBAL) {
983 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
984 $uid = $receiver['uid'];
988 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
990 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
991 if (!empty($contact['uid'])) {
992 $uid = $contact['uid'];
999 // @TODO Missing documentation
1000 public static function getReceiverURL(array $activity): array
1004 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1005 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1006 if (empty($receiver_list)) {
1010 foreach ($receiver_list as $receiver) {
1011 if ($receiver == self::PUBLIC_COLLECTION) {
1012 $receiver = ActivityPub::PUBLIC_COLLECTION;
1014 $urls[$element][] = $receiver;
1022 * Fetch the receiver list from an activity array
1024 * @param array $activity
1025 * @param string $actor
1026 * @param array $tags
1027 * @param boolean $fetch_unlisted
1029 * @return array with receivers (user id)
1030 * @throws \Exception
1032 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
1034 $reply = $receivers = $profile = [];
1036 // When it is an answer, we inherite the receivers from the parent
1037 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
1038 if (!empty($replyto)) {
1039 $reply = [$replyto];
1041 // Fix possibly wrong item URI (could be an answer to a plink uri)
1042 $fixedReplyTo = Item::getURIByLink($replyto);
1043 if (!empty($fixedReplyTo)) {
1044 $reply[] = $fixedReplyTo;
1048 // Fetch all posts that refer to the object id
1049 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
1050 if (!empty($object_id)) {
1051 $reply[] = $object_id;
1054 if (!empty($reply)) {
1055 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1056 while ($parent = Post::fetch($parents)) {
1057 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1059 DBA::close($parents);
1062 if (!empty($actor)) {
1063 $profile = APContact::getByURL($actor);
1064 $followers = $profile['followers'] ?? '';
1065 $is_forum = ($actor['type'] ?? '') == 'Group';
1066 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1068 Logger::info('Empty actor', ['activity' => $activity]);
1073 // We have to prevent false follower assumptions upon thread completions
1074 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1076 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1077 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1078 if (empty($receiver_list)) {
1082 foreach ($receiver_list as $receiver) {
1083 if ($receiver == self::PUBLIC_COLLECTION) {
1084 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1087 // Add receiver "-1" for unlisted posts
1088 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1089 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1092 // Fetch the receivers for the public and the followers collection
1093 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1094 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1098 // Fetching all directly addressed receivers
1099 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1100 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1101 if (!DBA::isResult($contact)) {
1105 // Check if the potential receiver is following the actor
1106 // Exception: The receiver is targetted via "to" or this is a comment
1107 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1108 $networks = Protocol::FEDERATED;
1109 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1110 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1112 // Forum posts are only accepted from forum contacts
1113 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1114 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1117 if (!DBA::exists('contact', $condition)) {
1122 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1123 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1126 $type = self::TARGET_TO;
1129 $type = self::TARGET_CC;
1132 $type = self::TARGET_BTO;
1135 $type = self::TARGET_BCC;
1139 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1144 self::switchContacts($receivers, $actor);
1150 * Fetch the receiver list of a given actor
1152 * @param string $actor
1153 * @param array $tags
1154 * @param array $receivers
1155 * @param integer $target_type
1156 * @param array $profile
1158 * @return array with receivers (user id)
1159 * @throws \Exception
1161 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1163 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1164 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1166 if (!empty($profile['uri-id'])) {
1167 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1168 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1169 while ($contact = DBA::fetch($contacts)) {
1170 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1171 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1174 DBA::close($contacts);
1176 // This part will only be called while post update 1426 wasn't finished
1177 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1178 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1179 while ($contact = DBA::fetch($contacts)) {
1180 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1181 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1184 DBA::close($contacts);
1186 // The queries are split because of performance issues
1187 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1188 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1189 while ($contact = DBA::fetch($contacts)) {
1190 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1191 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1194 DBA::close($contacts);
1200 * Tests if the contact is a valid receiver for this actor
1202 * @param array $contact
1203 * @param array $tags
1205 * @return bool with receivers (user id)
1206 * @throws \Exception
1208 private static function isValidReceiverForActor(array $contact, array $tags): bool
1210 // Are we following the contact? Then this is a valid receiver
1211 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1215 // When the possible receiver isn't a community, then it is no valid receiver
1216 $owner = User::getOwnerDataById($contact['uid']);
1217 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1221 // Is the community account tagged?
1222 foreach ($tags as $tag) {
1223 if ($tag['type'] != 'Mention') {
1227 if (Strings::compareLink($tag['href'], $owner['url'])) {
1236 * Switches existing contacts to ActivityPub
1238 * @param integer $cid Contact ID
1239 * @param integer $uid User ID
1240 * @param string $url Profile URL
1242 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1243 * @throws \ImagickException
1245 public static function switchContact(int $cid, int $uid, string $url)
1247 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1248 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1252 if (Contact::updateFromProbe($cid)) {
1253 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1256 // Send a new follow request to be sure that the connection still exists
1257 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1258 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1259 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1264 * @TODO Fix documentation and type-hints
1269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1270 * @throws \ImagickException
1272 private static function switchContacts($receivers, $actor)
1274 if (empty($actor)) {
1278 foreach ($receivers as $receiver) {
1279 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1280 if (DBA::isResult($contact)) {
1281 self::switchContact($contact['id'], $receiver['uid'], $actor);
1284 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1285 if (DBA::isResult($contact)) {
1286 self::switchContact($contact['id'], $receiver['uid'], $actor);
1292 * @TODO Fix documentation and type-hints
1294 * @param $object_data
1295 * @param array $activity
1299 private static function addActivityFields($object_data, array $activity)
1301 if (!empty($activity['published']) && empty($object_data['published'])) {
1302 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1305 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1306 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1309 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1310 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1312 if (!empty($object_data['object_id'])) {
1313 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1314 $objectId = Item::getURIByLink($object_data['object_id']);
1315 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1316 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1317 $object_data['object_id'] = $objectId;
1321 return $object_data;
1325 * Fetches the object data from external ressources if needed
1327 * @param string $object_id Object ID of the the provided object
1328 * @param array $object The provided object array
1329 * @param boolean $trust_source Do we trust the provided object?
1330 * @param integer $uid User ID for the signature that we use to fetch data
1332 * @return array|false with trusted and valid object data
1333 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1334 * @throws \ImagickException
1336 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1338 // By fetching the type we check if the object is complete.
1339 $type = JsonLD::fetchElement($object, '@type');
1341 if (!$trust_source || empty($type)) {
1342 $data = Processor::fetchCachedActivity($object_id, $uid);
1343 if (!empty($data)) {
1344 $object = JsonLD::compact($data);
1345 Logger::info('Fetched content for ' . $object_id);
1347 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1349 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1350 if (!DBA::isResult($item)) {
1351 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1354 Logger::info('Using already stored item for url ' . $object_id);
1355 $data = ActivityPub\Transmitter::createNote($item);
1356 $object = JsonLD::compact($data);
1359 $id = JsonLD::fetchElement($object, '@id');
1361 Logger::info('Empty id');
1365 if ($id != $object_id) {
1366 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1370 Logger::info('Using original object for url ' . $object_id);
1373 $type = JsonLD::fetchElement($object, '@type');
1375 Logger::info('Empty type');
1379 // Lemmy is resharing "create" activities instead of content
1380 // We fetch the content from the activity.
1381 if (in_array($type, ['as:Create'])) {
1382 $object = $object['as:object'];
1383 $type = JsonLD::fetchElement($object, '@type');
1385 Logger::info('Empty type');
1388 $object_data = self::processObject($object);
1391 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1392 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1393 $object_data = self::processObject($object);
1395 if (!empty($data)) {
1396 $object_data['raw-object'] = json_encode($data);
1398 return $object_data;
1401 if ($type == 'as:Announce') {
1402 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1403 if (empty($object_id) || !is_string($object_id)) {
1406 return self::fetchObject($object_id, [], false, $uid);
1409 Logger::info('Unhandled object type: ' . $type);
1414 * Converts the language element (Used by Peertube)
1416 * @param array $languages
1417 * @return array Languages
1419 public static function processLanguages(array $languages): array
1421 if (empty($languages)) {
1425 $language_list = [];
1427 foreach ($languages as $language) {
1428 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1429 $language_list[$language['_:identifier']] = $language['as:name'];
1432 return $language_list;
1436 * Convert tags from JSON-LD format into a simplified format
1438 * @param array $tags Tags in JSON-LD format
1440 * @return array with tags in a simplified format
1442 public static function processTags(array $tags): array
1446 foreach ($tags as $tag) {
1451 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1452 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1453 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1455 if (empty($element['type'])) {
1459 if (empty($element['href'])) {
1460 $element['href'] = $element['name'];
1463 $taglist[] = $element;
1469 * Convert emojis from JSON-LD format into a simplified format
1471 * @param array $emojis
1472 * @return array with emojis in a simplified format
1474 private static function processEmojis(array $emojis): array
1478 foreach ($emojis as $emoji) {
1479 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1483 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1484 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1487 $emojilist[] = $element;
1494 * Convert attachments from JSON-LD format into a simplified format
1496 * @param array $attachments Attachments in JSON-LD format
1498 * @return array Attachments in a simplified format
1500 private static function processAttachments(array $attachments): array
1504 // Removes empty values
1505 $attachments = array_filter($attachments);
1507 foreach ($attachments as $attachment) {
1508 switch (JsonLD::fetchElement($attachment, '@type')) {
1513 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1514 foreach ($urls as $url) {
1515 // Single scalar URL case
1516 if (is_string($url)) {
1521 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1522 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1523 if (Strings::startsWith($mediaType, 'image')) {
1532 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1533 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1535 'image' => $pageImage,
1539 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1540 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1541 $imagePreviewUrl = null;
1543 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1544 $imageVariants = [];
1545 $previewVariants = [];
1546 foreach ($urls as $url) {
1547 // Scalar URL, no discrimination possible
1548 if (is_string($url)) {
1549 $imageFullUrl = $url;
1553 // Not sure what to do with a different Link media type than the base Image, we skip
1554 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1558 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1560 // Default URL choice if no discriminating width is provided
1561 $imageFullUrl = $href ?? $imageFullUrl;
1563 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1565 if ($href && $width) {
1566 $imageVariants[$width] = $href;
1567 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1568 $previewVariants[abs(632 - $width)] = $href;
1572 if ($imageVariants) {
1573 // Taking the maximum size image
1574 ksort($imageVariants);
1575 $imageFullUrl = array_pop($imageVariants);
1577 // Taking the minimum number distance to the target distance
1578 ksort($previewVariants);
1579 $imagePreviewUrl = array_shift($previewVariants);
1582 unset($imageVariants);
1583 unset($previewVariants);
1587 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1588 'mediaType' => $mediaType,
1589 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1590 'url' => $imageFullUrl,
1591 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1596 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1597 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1598 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1599 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1600 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1601 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1602 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1611 * Convert questions from JSON-LD format into a simplified format
1613 * @param array $object
1615 * @return array Questions in a simplified format
1617 private static function processQuestion(array $object): array
1621 if (!empty($object['as:oneOf'])) {
1622 $question['multiple'] = false;
1623 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1624 } elseif (!empty($object['as:anyOf'])) {
1625 $question['multiple'] = true;
1626 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1631 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1632 if (!empty($closed)) {
1633 $question['end-time'] = $closed;
1635 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1638 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1639 $question['options'] = [];
1643 foreach ($options as $option) {
1644 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1648 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1650 if (empty($option['as:replies'])) {
1654 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1656 $question['options'][] = ['name' => $name, 'replies' => $replies];
1658 $voters += (int)$replies;
1661 // For single choice question we can count the number of voters if not provided (like with Misskey)
1662 if (empty($question['voters']) && !$question['multiple']) {
1663 $question['voters'] = $voters;
1670 * Fetch the original source or content with the "language" Markdown or HTML
1672 * @param array $object
1673 * @param array $object_data
1675 * @return array Object data (?)
1676 * @throws \Exception
1678 private static function getSource(array $object, array $object_data): array
1680 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1681 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1682 if (!empty($object_data['source'])) {
1683 return $object_data;
1686 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1687 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1688 if (!empty($object_data['source'])) {
1689 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1690 return $object_data;
1693 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1694 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1695 if (!empty($object_data['source'])) {
1696 $object_data['source'] = HTML::toBBCode($object_data['source']);
1697 return $object_data;
1700 return $object_data;
1704 * Extracts a potential alternate URL from a list of additional URL elements
1706 * @param array $urls
1709 private static function extractAlternateUrl(array $urls): string
1712 foreach ($urls as $key => $url) {
1713 // Not a list but a single URL element
1714 if (!is_numeric($key)) {
1718 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1722 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1727 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1728 if (empty($mediatype)) {
1732 if ($mediatype == 'text/html') {
1733 $alternateUrl = $href;
1737 return $alternateUrl;
1741 * Check if the "as:url" element is an array with multiple links
1742 * This is the case with audio and video posts.
1743 * Then the links are added as attachments
1745 * @param array $urls The object URL list
1746 * @return array an array of attachments
1748 private static function processAttachmentUrls(array $urls): array
1751 foreach ($urls as $key => $url) {
1752 // Not a list but a single URL element
1753 if (!is_numeric($key)) {
1757 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1761 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1766 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1767 if (empty($mediatype)) {
1771 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1773 if ($filetype == 'audio') {
1774 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1775 } elseif ($filetype == 'video') {
1776 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1777 // PeerTube audio-only track
1778 if ($height === 0) {
1782 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1783 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1784 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1785 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1787 // For Torrent links we always store the highest resolution
1788 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1792 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1793 } elseif ($mediatype == 'application/x-mpegURL') {
1794 // PeerTube exception, actual video link is in the tags of this URL element
1795 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1799 return array_values($attachments);
1803 * Fetches data from the object part of an activity
1805 * @param array $object
1807 * @return array|bool Object data or FALSE if $object does not contain @id element
1808 * @throws \Exception
1810 private static function processObject(array $object)
1812 if (!JsonLD::fetchElement($object, '@id')) {
1817 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1818 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1819 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1821 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1822 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1823 $object_data['reply-to-id'] = $object_data['id'];
1825 // On activities the "reply to" is the id of the object it refers to
1826 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1827 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1828 if (!empty($object_id)) {
1829 $object_data['reply-to-id'] = $object_id;
1833 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1834 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1835 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1836 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1837 $object_data['reply-to-id'] = $replyToId;
1841 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1842 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1844 if (empty($object_data['updated'])) {
1845 $object_data['updated'] = $object_data['published'];
1848 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1849 $object_data['published'] = $object_data['updated'];
1852 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1853 if (empty($actor)) {
1854 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1857 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1858 $location = JsonLD::fetchElement($location, 'location', '@value');
1860 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1861 // down to HTML and then finally format to plaintext.
1862 $location = Markdown::convert($location);
1863 $location = BBCode::toPlaintext($location);
1866 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1867 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1868 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1869 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1870 $object_data['actor'] = $object_data['author'] = $actor;
1871 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1872 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1873 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1874 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1875 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1876 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1877 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1878 $object_data = self::getSource($object, $object_data);
1879 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1880 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1881 $object_data['location'] = $location;
1882 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1883 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1884 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1885 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1886 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1887 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1888 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1889 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1890 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1891 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1892 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1894 // Special treatment for Hubzilla links
1895 if (is_array($object_data['alternate-url'])) {
1896 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1898 if (!is_string($object_data['alternate-url'])) {
1899 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1903 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1904 $object_data['alternate-url'] = null;
1907 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1908 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1909 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1912 // For page types we expect that the alternate url posts to some page.
1913 // So we add this to the attachments if it differs from the id.
1914 // Currently only Lemmy is using the page type.
1915 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1916 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1917 $object_data['alternate-url'] = null;
1920 if ($object_data['object_type'] == 'as:Question') {
1921 $object_data['question'] = self::processQuestion($object);
1924 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1925 $receivers = $reception_types = [];
1926 foreach ($receiverdata as $key => $data) {
1927 $receivers[$key] = $data['uid'];
1928 $reception_types[$data['uid']] = $data['type'] ?? 0;
1931 $object_data['receiver_urls'] = self::getReceiverURL($object);
1932 $object_data['receiver'] = $receivers;
1933 $object_data['reception_type'] = $reception_types;
1935 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1936 unset($object_data['receiver'][-1]);
1937 unset($object_data['reception_type'][-1]);
1939 return $object_data;
1943 * Add an object id to the list of arrived activities
1949 private static function addArrivedId(string $id)
1951 DBA::delete('arrived-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
1952 DBA::insert('arrived-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE);
1956 * Checks if the given object already arrived before
1962 private static function hasArrived(string $id): bool
1964 return DBA::exists('arrived-activity', ['object-id' => $id]);