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::notice('Invalid HTTP signature, message will not be trusted.', ['uid' => $uid, 'actor' => $actor, 'header' => $header, 'body' => $body]);
127 } elseif (empty($http_signer)) {
128 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
131 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
132 $signer = [$http_signer];
135 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
137 if ($http_signer === false) {
138 $trust_source = false;
139 } elseif (LDSignature::isSigned($activity)) {
140 $ld_signer = LDSignature::getSigner($activity);
141 if (empty($ld_signer)) {
142 Logger::info('Invalid JSON-LD signature from ' . $actor);
143 } elseif ($ld_signer != $http_signer) {
144 $signer[] = $ld_signer;
146 if (!empty($ld_signer && ($actor == $http_signer))) {
147 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
148 $trust_source = true;
149 } elseif (!empty($ld_signer)) {
150 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
151 $trust_source = true;
152 } elseif ($actor == $http_signer) {
153 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
154 $trust_source = true;
156 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
157 $trust_source = false;
159 } elseif ($actor == $http_signer) {
160 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
161 $trust_source = true;
163 Logger::info('No JSON-LD signature, different actor.');
164 $trust_source = false;
167 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
171 * Process incoming posts from relays
173 * @param array $activity
174 * @param string $actor
177 private static function processRelayPost(array $activity, string $actor)
179 $type = JsonLD::fetchElement($activity, '@type');
181 Logger::notice('Empty type', ['activity' => $activity, 'actor' => $actor]);
185 $object_type = JsonLD::fetchElement($activity, 'as:object', '@type') ?? '';
187 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
188 if (empty($object_id)) {
189 Logger::notice('No object id found', ['type' => $type, 'object_type' => $object_type, 'actor' => $actor, 'activity' => $activity]);
193 $handle = ($type == 'as:Announce');
195 if (!$handle && in_array($type, ['as:Create', 'as:Update'])) {
196 $handle = in_array($object_type, self::CONTENT_TYPES);
200 $trust_source = false;
201 $object_data = self::prepareObjectData($activity, 0, false, $trust_source);
203 if (!$trust_source) {
204 Logger::notice('Activity trust could not be achieved.', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
208 if (empty($object_data)) {
209 Logger::notice('No object data found', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
213 if (self::routeActivities($object_data, $type, true)) {
214 Logger::debug('Handled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor]);
216 Logger::info('Unhandled activity', ['type' => $type, 'object_type' => $object_type, 'object_id' => $object_id, 'actor' => $actor, 'activity' => $activity]);
221 $contact = Contact::getByURL($actor);
222 if (empty($contact)) {
223 Logger::info('Relay contact not found', ['actor' => $actor]);
227 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
228 Logger::notice('Relay is no sharer', ['actor' => $actor]);
232 Logger::debug('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
234 $item_id = Item::searchByLink($object_id);
236 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
240 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
242 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
248 * Fetches the object type for a given object id
250 * @param array $activity
251 * @param string $object_id Object ID of the the provided object
252 * @param integer $uid User ID
254 * @return string with object type or NULL
255 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
256 * @throws \ImagickException
258 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
260 if (!empty($activity['as:object'])) {
261 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
262 if (!empty($object_type)) {
267 if (Post::exists(['uri' => $object_id, 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT]])) {
268 // We just assume "note" since it doesn't make a difference for the further processing
272 $profile = APContact::getByURL($object_id);
273 if (!empty($profile['type'])) {
274 APContact::unmarkForArchival($profile);
275 return 'as:' . $profile['type'];
278 $data = Processor::fetchCachedActivity($object_id, $uid);
280 $object = JsonLD::compact($data);
281 $type = JsonLD::fetchElement($object, '@type');
291 * Prepare the object array
293 * @param array $activity Array with activity data
294 * @param integer $uid User ID
295 * @param boolean $push Message had been pushed to our system
296 * @param boolean $trust_source Do we trust the source?
298 * @return array with object data
299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
300 * @throws \ImagickException
302 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
304 $id = JsonLD::fetchElement($activity, '@id');
305 $type = JsonLD::fetchElement($activity, '@type');
306 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
308 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
309 $fetch_id = $object_id;
314 if (!empty($activity['as:object'])) {
315 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
318 if (!empty($id) && !$trust_source) {
319 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
321 $fetched_activity = Processor::fetchCachedActivity($fetch_id, $fetch_uid);
322 if (!empty($fetched_activity)) {
323 $object = JsonLD::compact($fetched_activity);
325 $fetched_id = JsonLD::fetchElement($object, '@id');
326 $fetched_type = JsonLD::fetchElement($object, '@type');
328 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
329 Logger::info('Activity had been fetched successfully', ['id' => $id]);
330 $trust_source = true;
332 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
333 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
334 $trust_source = true;
335 unset($object['@context']);
336 $activity['as:object'] = $object;
338 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
341 Logger::info('Activity could not been fetched', ['id' => $id]);
345 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
347 Logger::info('Empty actor', ['activity' => $activity]);
351 $type = JsonLD::fetchElement($activity, '@type');
353 // Fetch all receivers from to, cc, bto and bcc
354 $receiverdata = self::getReceivers($activity, $actor);
355 $receivers = $reception_types = [];
356 foreach ($receiverdata as $key => $data) {
357 $receivers[$key] = $data['uid'];
358 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
361 $urls = self::getReceiverURL($activity);
363 // When it is a delivery to a personal inbox we add that user to the receivers
365 $additional = [$uid => $uid];
366 $receivers = array_replace($receivers, $additional);
367 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]))) {
368 $reception_types[$uid] = self::TARGET_BCC;
369 $owner = User::getOwnerDataById($uid);
370 if (!empty($owner['url'])) {
371 $urls['as:bcc'][] = $owner['url'];
376 // We possibly need some user to fetch private content,
377 // so we fetch one out of the receivers if no uid is provided.
378 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
380 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
381 if (empty($object_id)) {
382 Logger::info('No object found');
386 if (!is_string($object_id)) {
387 Logger::info('Invalid object id', ['object' => $object_id]);
391 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
393 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
394 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
395 Logger::debug('Fetch announced activity', ['object' => $object_id]);
396 $data = Processor::fetchCachedActivity($object_id, $fetch_uid);
398 $type = $object_type;
399 $activity = JsonLD::compact($data);
401 // Some variables need to be refetched since the activity changed
402 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
403 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
404 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
408 // Any activities on account types must not be altered
409 if (in_array($type, ['as:Flag'])) {
411 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
412 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
413 $object_data['object_ids'] = JsonLD::fetchElementArray($activity, 'as:object', '@id');
414 $object_data['content'] = JsonLD::fetchElement($activity, 'as:content', '@type');
415 $object_data['push'] = $push;
416 } elseif (in_array($object_type, self::ACCOUNT_TYPES)) {
418 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
419 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
420 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
421 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
422 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
423 $object_data['push'] = $push;
424 if (!$trust_source && ($type == 'as:Delete')) {
425 $apcontact = APContact::getByURL($object_data['object_id'], true);
426 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
428 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
429 // Fetch the content only on activities where this matters
430 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
431 // Always fetch on "Announce"
432 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
433 if (empty($object_data)) {
434 Logger::info("Object data couldn't be processed");
438 $object_data['object_id'] = $object_id;
440 if ($type == 'as:Announce') {
441 $object_data['push'] = false;
443 $object_data['push'] = $push;
446 // Test if it is an answer to a mail
447 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
448 $object_data['directmessage'] = true;
450 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
452 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
453 // Create a mostly empty array out of the activity data (instead of the object).
454 // This way we later don't have to check for the existence of each individual array element.
455 $object_data = self::processObject($activity);
456 $object_data['name'] = $type;
457 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
458 $object_data['object_id'] = $object_id;
459 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
460 $object_data['push'] = $push;
461 } elseif (in_array($type, ['as:Add', 'as:Remove', 'as:Move'])) {
463 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
464 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
465 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
466 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
467 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
468 $object_data['push'] = $push;
471 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
472 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
473 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
474 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
475 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
476 $object_data['push'] = $push;
478 // An Undo is done on the object of an object, so we need that type as well
479 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
480 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
483 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
484 $trust_source = Processor::isActivityGone($object_data['object_id']);
485 if (!$trust_source) {
486 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
491 $object_data = self::addActivityFields($object_data, $activity);
493 if (empty($object_data['object_type'])) {
494 $object_data['object_type'] = $object_type;
497 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
498 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
499 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
503 $object_data['type'] = $type;
504 $object_data['actor'] = $actor;
505 $object_data['item_receiver'] = $receivers;
506 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
507 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
509 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
510 // $author = $object_data['author'] ?? $actor;
511 // if (!empty($author) && !empty($object_data['id'])) {
512 // $author_host = parse_url($author, PHP_URL_HOST);
513 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
514 // if ($author_host == $id_host) {
515 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
517 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
518 // $trust_source = false;
522 $account = Contact::selectFirstAccount(['platform'], ['nurl' => Strings::normaliseLink($actor)]);
523 $platform = $account['platform'] ?? '';
525 Logger::info('Processing', ['type' => $object_data['type'], 'object_type' => $object_data['object_type'], 'id' => $object_data['id'], 'actor' => $actor, 'platform' => $platform]);
531 * Fetches the first user id from the receiver array
533 * @param array $receivers Array with receivers
534 * @return integer user id;
536 public static function getFirstUserFromReceivers(array $receivers): int
538 foreach ($receivers as $receiver) {
539 if (!empty($receiver)) {
547 * Processes the activity object
549 * @param array $activity Array with activity data
550 * @param string $body The unprocessed body
551 * @param int|null $uid User ID
552 * @param boolean $trust_source Do we trust the source?
553 * @param boolean $push Message had been pushed to our system
554 * @param array $signer The signer of the post
558 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
559 * @throws \ImagickException
561 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
563 $type = JsonLD::fetchElement($activity, '@type');
565 Logger::info('Empty type', ['activity' => $activity]);
569 if ($type == 'as:View') {
570 Logger::info('View activities are ignored.', ['signer' => $signer, 'http_signer' => $http_signer]);
574 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
575 Logger::info('Empty object', ['activity' => $activity]);
579 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
581 Logger::info('Empty actor', ['activity' => $activity]);
585 if (is_array($activity['as:object'])) {
586 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
591 // Test the provided signatures against the actor and "attributedTo"
593 if (!empty($attributed_to) && !empty($actor)) {
594 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
596 $trust_source = in_array($actor, $signer);
600 // $trust_source is called by reference and is set to true if the content was retrieved successfully
601 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
602 if (empty($object_data)) {
603 Logger::info('No object data found', ['activity' => $activity]);
607 // Lemmy is announcing activities.
608 // We are changing the announces into regular activities.
609 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
610 Logger::debug('Change type of announce to activity', ['type' => $object_data['type']]);
611 $type = $object_data['type'];
614 if (!empty($body) && empty($object_data['raw'])) {
615 $object_data['raw'] = $body;
618 // Internal flag for thread completion. See Processor.php
619 if (!empty($activity['thread-completion'])) {
620 $object_data['thread-completion'] = $activity['thread-completion'];
623 if (!empty($activity['completion-mode'])) {
624 $object_data['completion-mode'] = $activity['completion-mode'];
627 if (!empty($activity['thread-children-type'])) {
628 $object_data['thread-children-type'] = $activity['thread-children-type'];
631 // Internal flag for posts that arrived via relay
632 if (!empty($activity['from-relay'])) {
633 $object_data['from-relay'] = $activity['from-relay'];
636 if ($type == 'as:Announce') {
637 $object_data['object_activity'] = $activity;
640 if (($type == 'as:Create') && $trust_source) {
641 if (self::hasArrived($object_data['object_id'])) {
642 Logger::info('The activity already arrived.', ['id' => $object_data['object_id']]);
645 self::addArrivedId($object_data['object_id']);
647 if (Queue::exists($object_data['object_id'], $type)) {
648 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
653 if (DI::config()->get('system', 'decoupled_receiver') && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
654 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
657 if (!$trust_source) {
658 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
662 if (!empty($object_data['entry-id']) && DI::config()->get('system', 'decoupled_receiver') && ($push || ($completion == self::COMPLETION_RELAY))) {
663 if (Queue::isProcessable($object_data['entry-id'])) {
664 // We delay by 5 seconds to allow to accumulate all receivers
665 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
666 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
667 $wid = Worker::add(['priority' => Worker::PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
668 Queue::setWorkerId($object_data['entry-id'], $wid);
670 Logger::debug('Other queue entries need to be processed first.', ['id' => $object_data['entry-id']]);
675 if (!empty($activity['recursion-depth'])) {
676 $object_data['recursion-depth'] = $activity['recursion-depth'];
679 if (!self::routeActivities($object_data, $type, $push)) {
680 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
681 Queue::remove($object_data);
689 * @param array $object_data
690 * @param string $type
692 * @param bool $fetch_parents
694 * @return boolean Could the activity be routed?
696 public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true): bool
698 $activity = $object_data['object_activity'] ?? [];
702 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
703 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
704 ActivityPub\Processor::postItem($object_data, $item);
705 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
706 // Unhandled Peertube activity
707 Queue::remove($object_data);
708 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
709 ActivityPub\Processor::updatePerson($object_data);
716 if (in_array($object_data['object_type'], ['as:Event'])) {
717 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
718 ActivityPub\Processor::postItem($object_data, $item);
725 if ($object_data['object_type'] == 'as:tag') {
726 ActivityPub\Processor::addTag($object_data);
727 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
728 ActivityPub\Processor::addToFeaturedCollection($object_data);
729 } elseif ($object_data['object_type'] == '') {
730 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
731 Queue::remove($object_data);
738 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
739 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
740 $object_data['thread-completion'] = Contact::getIdForURL($actor);
741 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
743 if (!Post::exists(['uri' => $object_data['id'], 'uid' => 0])) {
744 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
746 Logger::debug('announced id was not created', ['id' => $object_data['id']]);
747 Queue::remove($object_data);
751 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
752 ActivityPub\Processor::postItem($object_data, $item);
753 Logger::debug('Created announced id', ['id' => $object_data['id']]);
755 Logger::info('Announced id already exists', ['id' => $object_data['id']]);
756 Queue::remove($object_data);
759 if (!empty($activity)) {
760 $announce_object_data = self::processObject($activity);
761 $announce_object_data['name'] = $type;
762 $announce_object_data['author'] = $actor;
763 $announce_object_data['object_id'] = $object_data['id'];
764 $announce_object_data['object_type'] = $object_data['object_type'];
765 $announce_object_data['push'] = $push;
766 Logger::debug('Create announce activity', ['id' => $announce_object_data['id'], 'object_data' => $announce_object_data]);
768 if (!empty($object_data['raw'])) {
769 $announce_object_data['raw'] = $object_data['raw'];
771 if (!empty($object_data['raw-object'])) {
772 $announce_object_data['raw-object'] = $object_data['raw-object'];
774 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
782 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
783 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
784 } elseif (in_array($object_data['object_type'], ['', 'as:Tombstone'])) {
785 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
786 Queue::remove($object_data);
793 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
794 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
795 } elseif (in_array($object_data['object_type'], ['', 'as:Tombstone'])) {
796 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
797 Queue::remove($object_data);
803 case 'as:TentativeAccept':
804 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
805 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
812 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
813 ActivityPub\Processor::updateItem($object_data);
814 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
815 ActivityPub\Processor::updatePerson($object_data);
816 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
817 // Unhandled Peertube activity
818 Queue::remove($object_data);
825 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
826 ActivityPub\Processor::deleteItem($object_data);
827 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
828 ActivityPub\Processor::deletePerson($object_data);
829 } elseif ($object_data['object_type'] == '') {
830 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
831 Queue::remove($object_data);
838 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
839 ActivityPub\Processor::movePerson($object_data);
846 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
847 ActivityPub\Processor::blockAccount($object_data);
854 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
855 ActivityPub\Processor::ReportAccount($object_data);
862 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
863 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
864 } elseif ($object_data['object_type'] == '') {
865 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
866 Queue::remove($object_data);
873 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
874 ActivityPub\Processor::followUser($object_data);
875 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
876 $object_data['reply-to-id'] = $object_data['object_id'];
877 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
884 if ($object_data['object_type'] == 'as:Follow') {
885 if (!empty($object_data['object_actor'])) {
886 ActivityPub\Processor::acceptFollowUser($object_data);
888 Logger::notice('Unhandled "accept follow" message.', ['object_data' => $object_data]);
890 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
891 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
892 } elseif (!empty($object_data['object_id']) && empty($object_data['object_actor']) && empty($object_data['object_type'])) {
893 // Follow acceptances from gup.pe only contain the object id
894 ActivityPub\Processor::acceptFollowUser($object_data);
901 if ($object_data['object_type'] == 'as:Follow') {
902 ActivityPub\Processor::rejectFollowUser($object_data);
903 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
904 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
911 if (($object_data['object_type'] == 'as:Follow') &&
912 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
913 ActivityPub\Processor::undoFollowUser($object_data);
914 } elseif (($object_data['object_type'] == 'as:Follow') &&
915 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
916 ActivityPub\Processor::undoActivity($object_data);
917 } elseif (($object_data['object_type'] == 'as:Accept') &&
918 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
919 ActivityPub\Processor::rejectFollowUser($object_data);
920 } elseif (($object_data['object_type'] == 'as:Block') &&
921 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
922 ActivityPub\Processor::unblockAccount($object_data);
923 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
924 empty($object_data['object_object_type'])) {
925 // We cannot detect the target object. So we can ignore it.
926 Queue::remove($object_data);
927 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
928 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
929 ActivityPub\Processor::undoActivity($object_data);
930 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
931 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
932 // Unhandled Peertube activity
933 Queue::remove($object_data);
934 } elseif (in_array($object_data['object_type'], ['as:Delete'])) {
935 // We cannot undo deletions, so we just ignore this
936 Queue::remove($object_data);
943 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
944 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
945 } elseif ($object_data['object_type'] == '') {
946 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
947 Queue::remove($object_data);
953 case 'litepub:EmojiReact':
954 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
955 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
956 } elseif ($object_data['object_type'] == '') {
957 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
958 Queue::remove($object_data);
965 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
972 * Stores unhandled or unknown Activities as a file
974 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
975 * @param string $type Activity type
976 * @param array $object_data Preprocessed array that is generated out of the received activity
977 * @param array $activity Array with activity data
978 * @param string $body The unprocessed body
979 * @param integer $uid User ID
980 * @param boolean $trust_source Do we trust the source?
981 * @param boolean $push Message had been pushed to our system
982 * @param array $signer The signer of the post
985 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 = [])
987 if (!DI::config()->get('debug', 'ap_log_unknown')) {
991 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
993 if (!empty($object_data['object_type'])) {
994 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
997 if (!empty($object_data['object_object_type'])) {
998 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
1001 $tempfile = tempnam(System::getTempPath(), $file);
1002 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));
1003 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], 'object_object_type' => $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
1007 * Fetch a user id from an activity array
1009 * @param array $activity
1010 * @param string $actor
1012 * @return int user id
1014 public static function getBestUserForActivity(array $activity): int
1017 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
1019 $receivers = self::getReceivers($activity, $actor);
1020 foreach ($receivers as $receiver) {
1021 if ($receiver['type'] == self::TARGET_GLOBAL) {
1024 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
1025 $uid = $receiver['uid'];
1029 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
1031 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
1032 if (!empty($contact['uid'])) {
1033 $uid = $contact['uid'];
1040 // @TODO Missing documentation
1041 public static function getReceiverURL(array $activity): array
1045 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1046 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1047 if (empty($receiver_list)) {
1051 foreach ($receiver_list as $receiver) {
1052 if ($receiver == self::PUBLIC_COLLECTION) {
1053 $receiver = ActivityPub::PUBLIC_COLLECTION;
1055 $urls[$element][] = $receiver;
1063 * Fetch the receiver list from an activity array
1065 * @param array $activity
1066 * @param string $actor
1067 * @param array $tags
1068 * @param boolean $fetch_unlisted
1070 * @return array with receivers (user id)
1071 * @throws \Exception
1073 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
1075 $reply = $receivers = $profile = [];
1077 // When it is an answer, we inherite the receivers from the parent
1078 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
1079 if (!empty($replyto)) {
1080 $reply = [$replyto];
1082 // Fix possibly wrong item URI (could be an answer to a plink uri)
1083 $fixedReplyTo = Item::getURIByLink($replyto);
1084 if (!empty($fixedReplyTo)) {
1085 $reply[] = $fixedReplyTo;
1089 // Fetch all posts that refer to the object id
1090 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
1091 if (!empty($object_id)) {
1092 $reply[] = $object_id;
1095 if (!empty($reply)) {
1096 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1097 while ($parent = Post::fetch($parents)) {
1098 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1100 DBA::close($parents);
1103 if (!empty($actor)) {
1104 $profile = APContact::getByURL($actor);
1105 $followers = $profile['followers'] ?? '';
1106 $is_forum = ($actor['type'] ?? '') == 'Group';
1107 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1109 Logger::info('Empty actor', ['activity' => $activity]);
1114 // We have to prevent false follower assumptions upon thread completions
1115 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1117 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1118 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1119 if (empty($receiver_list)) {
1123 foreach ($receiver_list as $receiver) {
1124 if ($receiver == self::PUBLIC_COLLECTION) {
1125 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1128 // Add receiver "-1" for unlisted posts
1129 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1130 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1133 // Fetch the receivers for the public and the followers collection
1134 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1135 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1139 // Fetching all directly addressed receivers
1140 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1141 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1142 if (!DBA::isResult($contact)) {
1146 // Check if the potential receiver is following the actor
1147 // Exception: The receiver is targetted via "to" or this is a comment
1148 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1149 $networks = Protocol::FEDERATED;
1150 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1151 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1153 // Forum posts are only accepted from forum contacts
1154 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1155 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1158 if (!DBA::exists('contact', $condition)) {
1163 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1164 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1167 $type = self::TARGET_TO;
1170 $type = self::TARGET_CC;
1173 $type = self::TARGET_BTO;
1176 $type = self::TARGET_BCC;
1180 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1185 self::switchContacts($receivers, $actor);
1187 // "birdsitelive" is a service that mirrors tweets into the fediverse
1188 // These posts can be fetched without authentification, but are not marked as public
1189 // We treat them as unlisted posts to be able to handle them.
1190 if (empty($receivers) && $fetch_unlisted && Contact::isPlatform($actor, 'birdsitelive')) {
1191 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1192 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1193 Logger::notice('Post from "birdsitelive" is set to "unlisted"', ['id' => JsonLD::fetchElement($activity, '@id')]);
1194 } elseif (empty($receivers)) {
1195 Logger::notice('Post has got no receivers', ['fetch_unlisted' => $fetch_unlisted, 'actor' => $actor, 'id' => JsonLD::fetchElement($activity, '@id'), 'type' => JsonLD::fetchElement($activity, '@type')]);
1202 * Fetch the receiver list of a given actor
1204 * @param string $actor
1205 * @param array $tags
1206 * @param array $receivers
1207 * @param integer $target_type
1208 * @param array $profile
1210 * @return array with receivers (user id)
1211 * @throws \Exception
1213 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1215 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1216 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1218 if (!empty($profile['uri-id'])) {
1219 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1220 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1221 while ($contact = DBA::fetch($contacts)) {
1222 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1223 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1226 DBA::close($contacts);
1228 // This part will only be called while post update 1426 wasn't finished
1229 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1230 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1231 while ($contact = DBA::fetch($contacts)) {
1232 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1233 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1236 DBA::close($contacts);
1238 // The queries are split because of performance issues
1239 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1240 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1241 while ($contact = DBA::fetch($contacts)) {
1242 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1243 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1246 DBA::close($contacts);
1252 * Tests if the contact is a valid receiver for this actor
1254 * @param array $contact
1255 * @param array $tags
1257 * @return bool with receivers (user id)
1258 * @throws \Exception
1260 private static function isValidReceiverForActor(array $contact, array $tags): bool
1262 // Are we following the contact? Then this is a valid receiver
1263 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1267 // When the possible receiver isn't a community, then it is no valid receiver
1268 $owner = User::getOwnerDataById($contact['uid']);
1269 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1273 // Is the community account tagged?
1274 foreach ($tags as $tag) {
1275 if ($tag['type'] != 'Mention') {
1279 if (Strings::compareLink($tag['href'], $owner['url'])) {
1288 * Switches existing contacts to ActivityPub
1290 * @param integer $cid Contact ID
1291 * @param integer $uid User ID
1292 * @param string $url Profile URL
1294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1295 * @throws \ImagickException
1297 public static function switchContact(int $cid, int $uid, string $url)
1299 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1300 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1304 if (Contact::updateFromProbe($cid)) {
1305 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1308 // Send a new follow request to be sure that the connection still exists
1309 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1310 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1311 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1316 * @TODO Fix documentation and type-hints
1321 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1322 * @throws \ImagickException
1324 private static function switchContacts($receivers, $actor)
1326 if (empty($actor)) {
1330 foreach ($receivers as $receiver) {
1331 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1332 if (DBA::isResult($contact)) {
1333 self::switchContact($contact['id'], $receiver['uid'], $actor);
1336 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1337 if (DBA::isResult($contact)) {
1338 self::switchContact($contact['id'], $receiver['uid'], $actor);
1344 * @TODO Fix documentation and type-hints
1346 * @param $object_data
1347 * @param array $activity
1351 private static function addActivityFields($object_data, array $activity)
1353 if (!empty($activity['published']) && empty($object_data['published'])) {
1354 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1357 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1358 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1361 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1362 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1364 if (!empty($object_data['object_id'])) {
1365 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1366 $objectId = Item::getURIByLink($object_data['object_id']);
1367 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1368 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1369 $object_data['object_id'] = $objectId;
1373 return $object_data;
1377 * Fetches the object data from external ressources if needed
1379 * @param string $object_id Object ID of the the provided object
1380 * @param array $object The provided object array
1381 * @param boolean $trust_source Do we trust the provided object?
1382 * @param integer $uid User ID for the signature that we use to fetch data
1384 * @return array|false with trusted and valid object data
1385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1386 * @throws \ImagickException
1388 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1390 // By fetching the type we check if the object is complete.
1391 $type = JsonLD::fetchElement($object, '@type');
1393 if (!$trust_source || empty($type)) {
1394 $data = Processor::fetchCachedActivity($object_id, $uid);
1395 if (!empty($data)) {
1396 $object = JsonLD::compact($data);
1397 Logger::info('Fetched content for ' . $object_id);
1399 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1401 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1402 if (!DBA::isResult($item)) {
1403 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1406 Logger::info('Using already stored item for url ' . $object_id);
1407 $data = ActivityPub\Transmitter::createNote($item);
1408 $object = JsonLD::compact($data);
1411 $id = JsonLD::fetchElement($object, '@id');
1413 Logger::info('Empty id');
1417 if ($id != $object_id) {
1418 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1422 Logger::info('Using original object for url ' . $object_id);
1425 $type = JsonLD::fetchElement($object, '@type');
1427 Logger::info('Empty type');
1431 // Lemmy is resharing "create" activities instead of content
1432 // We fetch the content from the activity.
1433 if (in_array($type, ['as:Create'])) {
1434 $object = $object['as:object'];
1435 $type = JsonLD::fetchElement($object, '@type');
1437 Logger::info('Empty type');
1440 $object_data = self::processObject($object);
1443 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1444 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1445 $object_data = self::processObject($object);
1447 if (!empty($data)) {
1448 $object_data['raw-object'] = json_encode($data);
1450 return $object_data;
1453 if ($type == 'as:Announce') {
1454 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1455 if (empty($object_id) || !is_string($object_id)) {
1458 return self::fetchObject($object_id, [], false, $uid);
1461 Logger::info('Unhandled object type: ' . $type);
1466 * Converts the language element (Used by Peertube)
1468 * @param array $languages
1469 * @return array Languages
1471 public static function processLanguages(array $languages): array
1473 if (empty($languages)) {
1477 $language_list = [];
1479 foreach ($languages as $language) {
1480 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1481 $language_list[$language['_:identifier']] = $language['as:name'];
1484 return $language_list;
1488 * Convert tags from JSON-LD format into a simplified format
1490 * @param array $tags Tags in JSON-LD format
1492 * @return array with tags in a simplified format
1494 public static function processTags(array $tags): array
1498 foreach ($tags as $tag) {
1503 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type') ?? ''),
1504 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1505 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1507 if (empty($element['type'])) {
1511 if (empty($element['href'])) {
1512 $element['href'] = $element['name'];
1515 $taglist[] = $element;
1521 * Convert emojis from JSON-LD format into a simplified format
1523 * @param array $emojis
1524 * @return array with emojis in a simplified format
1526 private static function processEmojis(array $emojis): array
1530 foreach ($emojis as $emoji) {
1531 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1535 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1536 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1539 $emojilist[] = $element;
1546 * Convert attachments from JSON-LD format into a simplified format
1548 * @param array $attachments Attachments in JSON-LD format
1550 * @return array Attachments in a simplified format
1552 private static function processAttachments(array $attachments): array
1556 // Removes empty values
1557 $attachments = array_filter($attachments);
1559 foreach ($attachments as $attachment) {
1560 switch (JsonLD::fetchElement($attachment, '@type')) {
1565 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1566 foreach ($urls as $url) {
1567 // Single scalar URL case
1568 if (is_string($url)) {
1573 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1574 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1575 if (Strings::startsWith($mediaType, 'image')) {
1584 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1585 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1587 'image' => $pageImage,
1591 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1592 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1593 $imagePreviewUrl = null;
1595 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1596 $imageVariants = [];
1597 $previewVariants = [];
1598 foreach ($urls as $url) {
1599 // Scalar URL, no discrimination possible
1600 if (is_string($url)) {
1601 $imageFullUrl = $url;
1605 // Not sure what to do with a different Link media type than the base Image, we skip
1606 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1610 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1612 // Default URL choice if no discriminating width is provided
1613 $imageFullUrl = $href ?? $imageFullUrl;
1615 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1617 if ($href && $width) {
1618 $imageVariants[$width] = $href;
1619 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1620 $previewVariants[abs(632 - $width)] = $href;
1624 if ($imageVariants) {
1625 // Taking the maximum size image
1626 ksort($imageVariants);
1627 $imageFullUrl = array_pop($imageVariants);
1629 // Taking the minimum number distance to the target distance
1630 ksort($previewVariants);
1631 $imagePreviewUrl = array_shift($previewVariants);
1634 unset($imageVariants);
1635 unset($previewVariants);
1639 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1640 'mediaType' => $mediaType,
1641 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1642 'url' => $imageFullUrl,
1643 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1648 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1649 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1650 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1651 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1652 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1653 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1654 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1663 * Convert questions from JSON-LD format into a simplified format
1665 * @param array $object
1667 * @return array Questions in a simplified format
1669 private static function processQuestion(array $object): array
1673 if (!empty($object['as:oneOf'])) {
1674 $question['multiple'] = false;
1675 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1676 } elseif (!empty($object['as:anyOf'])) {
1677 $question['multiple'] = true;
1678 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1683 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1684 if (!empty($closed)) {
1685 $question['end-time'] = $closed;
1687 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1690 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1691 $question['options'] = [];
1695 foreach ($options as $option) {
1696 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1700 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1702 if (empty($option['as:replies'])) {
1706 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1708 $question['options'][] = ['name' => $name, 'replies' => $replies];
1710 $voters += (int)$replies;
1713 // For single choice question we can count the number of voters if not provided (like with Misskey)
1714 if (empty($question['voters']) && !$question['multiple']) {
1715 $question['voters'] = $voters;
1722 * Fetch the original source or content with the "language" Markdown or HTML
1724 * @param array $object
1725 * @param array $object_data
1727 * @return array Object data (?)
1728 * @throws \Exception
1730 private static function getSource(array $object, array $object_data): array
1732 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1733 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1734 if (!empty($object_data['source'])) {
1735 return $object_data;
1738 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1739 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1740 if (!empty($object_data['source'])) {
1741 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1742 return $object_data;
1745 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1746 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1747 if (!empty($object_data['source'])) {
1748 $object_data['source'] = HTML::toBBCode($object_data['source']);
1749 return $object_data;
1752 return $object_data;
1756 * Extracts a potential alternate URL from a list of additional URL elements
1758 * @param array $urls
1761 private static function extractAlternateUrl(array $urls): string
1764 foreach ($urls as $key => $url) {
1765 // Not a list but a single URL element
1766 if (!is_numeric($key)) {
1770 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1774 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1779 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1780 if (empty($mediatype)) {
1784 if ($mediatype == 'text/html') {
1785 $alternateUrl = $href;
1789 return $alternateUrl;
1793 * Check if the "as:url" element is an array with multiple links
1794 * This is the case with audio and video posts.
1795 * Then the links are added as attachments
1797 * @param array $urls The object URL list
1798 * @return array an array of attachments
1800 private static function processAttachmentUrls(array $urls): array
1803 foreach ($urls as $key => $url) {
1804 // Not a list but a single URL element
1805 if (!is_numeric($key)) {
1809 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1813 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1818 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1819 if (empty($mediatype)) {
1823 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1825 if ($filetype == 'audio') {
1826 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1827 } elseif ($filetype == 'video') {
1828 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1829 // PeerTube audio-only track
1830 if ($height === 0) {
1834 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1835 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1836 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1837 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1839 // For Torrent links we always store the highest resolution
1840 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1844 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1845 } elseif ($mediatype == 'application/x-mpegURL') {
1846 // PeerTube exception, actual video link is in the tags of this URL element
1847 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1851 return array_values($attachments);
1855 * Fetches data from the object part of an activity
1857 * @param array $object
1859 * @return array|bool Object data or FALSE if $object does not contain @id element
1860 * @throws \Exception
1862 private static function processObject(array $object)
1864 if (!JsonLD::fetchElement($object, '@id')) {
1869 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1870 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1871 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1873 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1874 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1875 $object_data['reply-to-id'] = $object_data['id'];
1877 // On activities the "reply to" is the id of the object it refers to
1878 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1879 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1880 if (!empty($object_id)) {
1881 $object_data['reply-to-id'] = $object_id;
1885 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1886 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1887 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1888 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1889 $object_data['reply-to-id'] = $replyToId;
1893 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1894 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1896 if (empty($object_data['updated'])) {
1897 $object_data['updated'] = $object_data['published'];
1900 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1901 $object_data['published'] = $object_data['updated'];
1904 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1905 if (empty($actor)) {
1906 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1909 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1910 $location = JsonLD::fetchElement($location, 'location', '@value');
1912 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1913 // down to HTML and then finally format to plaintext.
1914 $location = Markdown::convert($location);
1915 $location = BBCode::toPlaintext($location);
1918 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1919 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1920 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1921 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1922 $object_data['actor'] = $object_data['author'] = $actor;
1923 $element = JsonLD::fetchElement($object, 'as:context', '@id');
1924 $object_data['context'] = $element != './' ? $element : null;
1925 $element = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1926 $object_data['conversation'] = $element != './' ? $element : null;
1927 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1928 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1929 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1930 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1931 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1932 $object_data = self::getSource($object, $object_data);
1933 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1934 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1935 $object_data['location'] = $location;
1936 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1937 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1938 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1939 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1940 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1941 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1942 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1943 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1944 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1945 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1946 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1948 // Special treatment for Hubzilla links
1949 if (is_array($object_data['alternate-url'])) {
1950 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1952 if (!is_string($object_data['alternate-url'])) {
1953 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1957 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1958 $object_data['alternate-url'] = null;
1961 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1962 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1963 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1966 // Support for quoted posts (Pleroma, Fedibird and Misskey)
1967 $object_data['quote-url'] = JsonLD::fetchElement($object, 'as:quoteUrl', '@value');
1968 if (empty($object_data['quote-url'])) {
1969 $object_data['quote-url'] = JsonLD::fetchElement($object, 'fedibird:quoteUri', '@value');
1971 if (empty($object_data['quote-url'])) {
1972 $object_data['quote-url'] = JsonLD::fetchElement($object, 'misskey:_misskey_quote', '@value');
1975 // Misskey adds some data to the standard "content" value for quoted posts for backwards compatibility.
1976 // Their own "_misskey_content" value does then contain the content without this extra data.
1977 if (!empty($object_data['quote-url'])) {
1978 $misskey_content = JsonLD::fetchElement($object, 'misskey:_misskey_content', '@value');
1979 if (!empty($misskey_content)) {
1980 $object_data['content'] = $misskey_content;
1984 // For page types we expect that the alternate url posts to some page.
1985 // So we add this to the attachments if it differs from the id.
1986 // Currently only Lemmy is using the page type.
1987 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1988 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1989 $object_data['alternate-url'] = null;
1992 if ($object_data['object_type'] == 'as:Question') {
1993 $object_data['question'] = self::processQuestion($object);
1996 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1997 $receivers = $reception_types = [];
1998 foreach ($receiverdata as $key => $data) {
1999 $receivers[$key] = $data['uid'];
2000 $reception_types[$data['uid']] = $data['type'] ?? 0;
2003 $object_data['receiver_urls'] = self::getReceiverURL($object);
2004 $object_data['receiver'] = $receivers;
2005 $object_data['reception_type'] = $reception_types;
2007 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
2008 unset($object_data['receiver'][-1]);
2009 unset($object_data['reception_type'][-1]);
2011 return $object_data;
2015 * Add an object id to the list of arrived activities
2021 private static function addArrivedId(string $id)
2023 DBA::delete('arrived-activity', ["`received` < ?", DateTimeFormat::utc('now - 5 minutes')]);
2024 DBA::insert('arrived-activity', ['object-id' => $id, 'received' => DateTimeFormat::utcNow()], Database::INSERT_IGNORE);
2028 * Checks if the given object already arrived before
2034 private static function hasArrived(string $id): bool
2036 return DBA::exists('arrived-activity', ['object-id' => $id]);