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;
32 use Friendica\Model\Contact;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Util\HTTPSignature;
40 use Friendica\Util\JsonLD;
41 use Friendica\Util\LDSignature;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
46 * ActivityPub Receiver Protocol class
51 * Check what this is meant to do:
60 const PUBLIC_COLLECTION = 'as:Public';
61 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
62 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
63 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
65 const TARGET_UNKNOWN = 0;
70 const TARGET_FOLLOWER = 5;
71 const TARGET_ANSWER = 6;
72 const TARGET_GLOBAL = 7;
74 const COMPLETION_NONE = 0;
75 const COMPLETION_ANNOUCE = 1;
76 const COMPLETION_RELAY = 2;
77 const COMPLETION_MANUAL = 3;
78 const COMPLETION_AUTO = 4;
81 * Checks incoming message from the inbox
83 * @param string $body Body string
84 * @param array $header Header lines
85 * @param integer $uid User ID
89 public static function processInbox(string $body, array $header, int $uid)
91 $activity = json_decode($body, true);
92 if (empty($activity)) {
93 Logger::warning('Invalid body.');
97 $ldactivity = JsonLD::compact($activity);
99 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
101 $apcontact = APContact::getByURL($actor);
103 if (empty($apcontact)) {
104 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
106 } elseif (APContact::isRelay($apcontact)) {
107 self::processRelayPost($ldactivity, $actor);
110 APContact::unmarkForArchival($apcontact);
113 $http_signer = HTTPSignature::getSigner($body, $header);
114 if ($http_signer === false) {
115 Logger::warning('Invalid HTTP signature, message will be discarded.');
117 } elseif (empty($http_signer)) {
118 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
121 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
124 $signer = [$http_signer];
126 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
128 if (LDSignature::isSigned($activity)) {
129 $ld_signer = LDSignature::getSigner($activity);
130 if (empty($ld_signer)) {
131 Logger::info('Invalid JSON-LD signature from ' . $actor);
132 } elseif ($ld_signer != $http_signer) {
133 $signer[] = $ld_signer;
135 if (!empty($ld_signer && ($actor == $http_signer))) {
136 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
137 $trust_source = true;
138 } elseif (!empty($ld_signer)) {
139 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
140 $trust_source = true;
141 } elseif ($actor == $http_signer) {
142 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
143 $trust_source = true;
145 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
146 $trust_source = false;
148 } elseif ($actor == $http_signer) {
149 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
150 $trust_source = true;
152 Logger::info('No JSON-LD signature, different actor.');
153 $trust_source = false;
156 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
160 * Process incoming posts from relays
162 * @param array $activity
163 * @param string $actor
166 private static function processRelayPost(array $activity, string $actor)
168 $type = JsonLD::fetchElement($activity, '@type');
170 Logger::info('Empty type', ['activity' => $activity, 'actor' => $actor]);
174 if ($type != 'as:Announce') {
175 Logger::info('Not an announcement', ['activity' => $activity, 'actor' => $actor]);
179 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
180 if (empty($object_id)) {
181 Logger::info('No object id found', ['activity' => $activity, 'actor' => $actor]);
185 $contact = Contact::getByURL($actor);
186 if (empty($contact)) {
187 Logger::info('Relay contact not found', ['actor' => $actor]);
191 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
192 Logger::notice('Relay is no sharer', ['actor' => $actor]);
196 Logger::info('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
198 $item_id = Item::searchByLink($object_id);
200 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
204 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
206 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
210 $item_id = Item::searchByLink($object_id);
212 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
214 Logger::notice('Relayed message had not been stored', ['id' => $object_id, 'actor' => $actor]);
219 * Fetches the object type for a given object id
221 * @param array $activity
222 * @param string $object_id Object ID of the the provided object
223 * @param integer $uid User ID
225 * @return string with object type or NULL
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @throws \ImagickException
229 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
231 if (!empty($activity['as:object'])) {
232 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
233 if (!empty($object_type)) {
238 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
239 // We just assume "note" since it doesn't make a difference for the further processing
243 $profile = APContact::getByURL($object_id);
244 if (!empty($profile['type'])) {
245 APContact::unmarkForArchival($profile);
246 return 'as:' . $profile['type'];
249 $data = ActivityPub::fetchContent($object_id, $uid);
251 $object = JsonLD::compact($data);
252 $type = JsonLD::fetchElement($object, '@type');
262 * Prepare the object array
264 * @param array $activity Array with activity data
265 * @param integer $uid User ID
266 * @param boolean $push Message had been pushed to our system
267 * @param boolean $trust_source Do we trust the source?
269 * @return array with object data
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 * @throws \ImagickException
273 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
275 $id = JsonLD::fetchElement($activity, '@id');
276 if (!empty($id) && !$trust_source) {
277 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
279 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
280 if (!empty($fetched_activity)) {
281 $object = JsonLD::compact($fetched_activity);
282 $fetched_id = JsonLD::fetchElement($object, '@id');
283 if ($fetched_id == $id) {
284 Logger::info('Activity had been fetched successfully', ['id' => $id]);
285 $trust_source = true;
288 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
291 Logger::info('Activity could not been fetched', ['id' => $id]);
295 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
297 Logger::info('Empty actor', ['activity' => $activity]);
301 $type = JsonLD::fetchElement($activity, '@type');
303 // Fetch all receivers from to, cc, bto and bcc
304 $receiverdata = self::getReceivers($activity, $actor);
305 $receivers = $reception_types = [];
306 foreach ($receiverdata as $key => $data) {
307 $receivers[$key] = $data['uid'];
308 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
311 $urls = self::getReceiverURL($activity);
313 // When it is a delivery to a personal inbox we add that user to the receivers
315 $additional = [$uid => $uid];
316 $receivers = array_replace($receivers, $additional);
317 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]))) {
318 $reception_types[$uid] = self::TARGET_BCC;
319 $owner = User::getOwnerDataById($uid);
320 if (!empty($owner['url'])) {
321 $urls['as:bcc'][] = $owner['url'];
326 // We possibly need some user to fetch private content,
327 // so we fetch one out of the receivers if no uid is provided.
328 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
330 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
331 if (empty($object_id)) {
332 Logger::info('No object found');
336 if (!is_string($object_id)) {
337 Logger::info('Invalid object id', ['object' => $object_id]);
341 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
343 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
344 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
345 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
347 $type = $object_type;
348 $activity = JsonLD::compact($data);
350 // Some variables need to be refetched since the activity changed
351 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
352 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
353 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
357 // Any activities on account types must not be altered
358 if (in_array($object_type, self::ACCOUNT_TYPES)) {
360 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
361 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
362 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
363 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
364 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
365 $object_data['push'] = $push;
366 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
367 // Fetch the content only on activities where this matters
368 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
369 // Always fetch on "Announce"
370 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
371 if (empty($object_data)) {
372 Logger::info("Object data couldn't be processed");
376 $object_data['object_id'] = $object_id;
378 if ($type == 'as:Announce') {
379 $object_data['push'] = false;
381 $object_data['push'] = $push;
384 // Test if it is an answer to a mail
385 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
386 $object_data['directmessage'] = true;
388 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
390 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
391 // Create a mostly empty array out of the activity data (instead of the object).
392 // This way we later don't have to check for the existence of each individual array element.
393 $object_data = self::processObject($activity);
394 $object_data['name'] = $type;
395 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
396 $object_data['object_id'] = $object_id;
397 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
398 $object_data['push'] = $push;
399 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
401 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
402 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
403 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
404 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
405 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
406 $object_data['push'] = $push;
409 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
410 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
411 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
412 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
413 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
414 $object_data['push'] = $push;
416 // An Undo is done on the object of an object, so we need that type as well
417 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
418 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
422 $object_data = self::addActivityFields($object_data, $activity);
424 if (empty($object_data['object_type'])) {
425 $object_data['object_type'] = $object_type;
428 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
429 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
430 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
434 $object_data['type'] = $type;
435 $object_data['actor'] = $actor;
436 $object_data['item_receiver'] = $receivers;
437 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
438 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
440 $author = $object_data['author'] ?? $actor;
441 if (!empty($author) && !empty($object_data['id'])) {
442 $author_host = parse_url($author, PHP_URL_HOST);
443 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
444 if ($author_host == $id_host) {
445 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
447 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
448 $trust_source = false;
452 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
458 * Fetches the first user id from the receiver array
460 * @param array $receivers Array with receivers
461 * @return integer user id;
463 public static function getFirstUserFromReceivers(array $receivers): int
465 foreach ($receivers as $receiver) {
466 if (!empty($receiver)) {
474 * Processes the activity object
476 * @param array $activity Array with activity data
477 * @param string $body The unprocessed body
478 * @param int|null $uid User ID
479 * @param boolean $trust_source Do we trust the source?
480 * @param boolean $push Message had been pushed to our system
481 * @param array $signer The signer of the post
482 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
483 * @throws \ImagickException
485 public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '')
487 $type = JsonLD::fetchElement($activity, '@type');
489 Logger::info('Empty type', ['activity' => $activity]);
493 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
494 Logger::info('Empty object', ['activity' => $activity]);
498 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
500 Logger::info('Empty actor', ['activity' => $activity]);
504 if (is_array($activity['as:object'])) {
505 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
510 // Test the provided signatures against the actor and "attributedTo"
512 if (!empty($attributed_to) && !empty($actor)) {
513 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
515 $trust_source = in_array($actor, $signer);
519 // $trust_source is called by reference and is set to true if the content was retrieved successfully
520 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
521 if (empty($object_data)) {
522 Logger::info('No object data found', ['activity' => $activity]);
526 // Lemmy is announcing activities.
527 // We are changing the announces into regular activities.
528 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
529 $type = $object_data['type'];
532 if (!$trust_source) {
533 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
537 if (!empty($body) && empty($object_data['raw'])) {
538 $object_data['raw'] = $body;
541 // Internal flag for thread completion. See Processor.php
542 if (!empty($activity['thread-completion'])) {
543 $object_data['thread-completion'] = $activity['thread-completion'];
546 if (!empty($activity['completion-mode'])) {
547 $object_data['completion-mode'] = $activity['completion-mode'];
550 if (!empty($activity['thread-children-type'])) {
551 $object_data['thread-children-type'] = $activity['thread-children-type'];
554 if (!empty($activity['recursion-depth'])) {
555 $object_data['recursion-depth'] = $activity['recursion-depth'];
558 // Internal flag for posts that arrived via relay
559 if (!empty($activity['from-relay'])) {
560 $object_data['from-relay'] = $activity['from-relay'];
563 if ($type == 'as:Announce') {
564 $object_data['object_activity'] = $activity;
567 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push);
569 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
570 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
573 if (!self::routeActivities($object_data, $type, $push)) {
574 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
575 //if (!DI::config()->get('debug', 'ap_log_unknown')) {
576 // Queue::remove($object_data);
581 public static function routeActivities($object_data, $type, $push)
583 $activity = $object_data['object_activity'] ?? [];
587 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
588 $item = ActivityPub\Processor::createItem($object_data);
589 ActivityPub\Processor::postItem($object_data, $item);
590 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
591 // Unhandled Peertube activity
592 Queue::remove($object_data);
599 if (in_array($object_data['object_type'], ['as:Event'])) {
600 $item = ActivityPub\Processor::createItem($object_data);
601 ActivityPub\Processor::postItem($object_data, $item);
608 if ($object_data['object_type'] == 'as:tag') {
609 ActivityPub\Processor::addTag($object_data);
610 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
611 ActivityPub\Processor::addToFeaturedCollection($object_data);
612 } elseif ($object_data['object_type'] == '') {
613 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
614 Queue::remove($object_data);
621 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
622 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
623 $object_data['thread-completion'] = Contact::getIdForURL($actor);
624 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
626 $item = ActivityPub\Processor::createItem($object_data);
631 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
632 ActivityPub\Processor::postItem($object_data, $item);
634 if (!empty($activity)) {
635 $announce_object_data = self::processObject($activity);
636 $announce_object_data['name'] = $type;
637 $announce_object_data['author'] = $actor;
638 $announce_object_data['object_id'] = $object_data['object_id'];
639 $announce_object_data['object_type'] = $object_data['object_type'];
640 $announce_object_data['push'] = $push;
642 if (!empty($object_data['raw'])) {
643 $announce_object_data['raw'] = $object_data['raw'];
645 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
646 } else echo "\n***************************\n";
653 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
654 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
655 } elseif ($object_data['object_type'] == '') {
656 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
657 Queue::remove($object_data);
664 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
665 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
666 } elseif ($object_data['object_type'] == '') {
667 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
668 Queue::remove($object_data);
674 case 'as:TentativeAccept':
675 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
676 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
683 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
684 ActivityPub\Processor::updateItem($object_data);
685 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
686 ActivityPub\Processor::updatePerson($object_data);
687 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
688 // Unhandled Peertube activity
689 Queue::remove($object_data);
696 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
697 ActivityPub\Processor::deleteItem($object_data);
698 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
699 ActivityPub\Processor::deletePerson($object_data);
700 } elseif ($object_data['object_type'] == '') {
701 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
702 Queue::remove($object_data);
709 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
710 ActivityPub\Processor::blockAccount($object_data);
717 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
718 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
719 } elseif ($object_data['object_type'] == '') {
720 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
721 Queue::remove($object_data);
728 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
729 ActivityPub\Processor::followUser($object_data);
730 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
731 $object_data['reply-to-id'] = $object_data['object_id'];
732 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
739 if ($object_data['object_type'] == 'as:Follow') {
740 ActivityPub\Processor::acceptFollowUser($object_data);
741 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
742 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
749 if ($object_data['object_type'] == 'as:Follow') {
750 ActivityPub\Processor::rejectFollowUser($object_data);
751 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
752 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
759 if (($object_data['object_type'] == 'as:Follow') &&
760 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
761 ActivityPub\Processor::undoFollowUser($object_data);
762 } elseif (($object_data['object_type'] == 'as:Follow') &&
763 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
764 ActivityPub\Processor::undoActivity($object_data);
765 } elseif (($object_data['object_type'] == 'as:Accept') &&
766 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
767 ActivityPub\Processor::rejectFollowUser($object_data);
768 } elseif (($object_data['object_type'] == 'as:Block') &&
769 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
770 ActivityPub\Processor::unblockAccount($object_data);
771 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
772 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
773 ActivityPub\Processor::undoActivity($object_data);
774 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
775 empty($object_data['object_object_type'])) {
776 // We cannot detect the target object. So we can ignore it.
777 Queue::remove($object_data);
778 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
779 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
780 // Unhandled Peertube activity
781 Queue::remove($object_data);
788 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
789 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
790 } elseif ($object_data['object_type'] == '') {
791 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
792 Queue::remove($object_data);
798 case 'litepub:EmojiReact':
799 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
800 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
801 } elseif ($object_data['object_type'] == '') {
802 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
803 Queue::remove($object_data);
810 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
817 * Stores unhandled or unknown Activities as a file
819 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
820 * @param string $type Activity type
821 * @param array $object_data Preprocessed array that is generated out of the received activity
822 * @param array $activity Array with activity data
823 * @param string $body The unprocessed body
824 * @param integer $uid User ID
825 * @param boolean $trust_source Do we trust the source?
826 * @param boolean $push Message had been pushed to our system
827 * @param array $signer The signer of the post
830 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 = [])
832 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
834 if (!empty($object_data['object_type'])) {
835 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
838 if (!empty($object_data['object_object_type'])) {
839 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
842 $tempfile = tempnam(System::getTempPath(), $file);
843 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));
844 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
848 * Fetch a user id from an activity array
850 * @param array $activity
851 * @param string $actor
853 * @return int user id
855 public static function getBestUserForActivity(array $activity): int
858 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
860 $receivers = self::getReceivers($activity, $actor);
861 foreach ($receivers as $receiver) {
862 if ($receiver['type'] == self::TARGET_GLOBAL) {
865 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
866 $uid = $receiver['uid'];
870 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
872 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
873 if (!empty($contact['uid'])) {
874 $uid = $contact['uid'];
881 // @TODO Missing documentation
882 public static function getReceiverURL(array $activity): array
886 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
887 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
888 if (empty($receiver_list)) {
892 foreach ($receiver_list as $receiver) {
893 if ($receiver == self::PUBLIC_COLLECTION) {
894 $receiver = ActivityPub::PUBLIC_COLLECTION;
896 $urls[$element][] = $receiver;
904 * Fetch the receiver list from an activity array
906 * @param array $activity
907 * @param string $actor
909 * @param boolean $fetch_unlisted
911 * @return array with receivers (user id)
914 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
916 $reply = $receivers = $profile = [];
918 // When it is an answer, we inherite the receivers from the parent
919 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
920 if (!empty($replyto)) {
923 // Fix possibly wrong item URI (could be an answer to a plink uri)
924 $fixedReplyTo = Item::getURIByLink($replyto);
925 if (!empty($fixedReplyTo)) {
926 $reply[] = $fixedReplyTo;
930 // Fetch all posts that refer to the object id
931 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
932 if (!empty($object_id)) {
933 $reply[] = $object_id;
936 if (!empty($reply)) {
937 $parents = Post::select(['uid'], ['uri' => $reply]);
938 while ($parent = Post::fetch($parents)) {
939 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
941 DBA::close($parents);
944 if (!empty($actor)) {
945 $profile = APContact::getByURL($actor);
946 $followers = $profile['followers'] ?? '';
947 $is_forum = ($actor['type'] ?? '') == 'Group';
948 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
950 Logger::info('Empty actor', ['activity' => $activity]);
955 // We have to prevent false follower assumptions upon thread completions
956 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
958 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
959 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
960 if (empty($receiver_list)) {
964 foreach ($receiver_list as $receiver) {
965 if ($receiver == self::PUBLIC_COLLECTION) {
966 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
969 // Add receiver "-1" for unlisted posts
970 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
971 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
974 // Fetch the receivers for the public and the followers collection
975 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
976 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
980 // Fetching all directly addressed receivers
981 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
982 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
983 if (!DBA::isResult($contact)) {
987 // Check if the potential receiver is following the actor
988 // Exception: The receiver is targetted via "to" or this is a comment
989 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
990 $networks = Protocol::FEDERATED;
991 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
992 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
994 // Forum posts are only accepted from forum contacts
995 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
996 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
999 if (!DBA::exists('contact', $condition)) {
1004 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1005 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1008 $type = self::TARGET_TO;
1011 $type = self::TARGET_CC;
1014 $type = self::TARGET_BTO;
1017 $type = self::TARGET_BCC;
1021 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1026 self::switchContacts($receivers, $actor);
1032 * Fetch the receiver list of a given actor
1034 * @param string $actor
1035 * @param array $tags
1036 * @param array $receivers
1037 * @param integer $target_type
1038 * @param array $profile
1040 * @return array with receivers (user id)
1041 * @throws \Exception
1043 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1045 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1046 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1048 if (!empty($profile['uri-id'])) {
1049 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1050 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1051 while ($contact = DBA::fetch($contacts)) {
1052 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1053 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1056 DBA::close($contacts);
1058 // This part will only be called while post update 1426 wasn't finished
1059 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1060 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1061 while ($contact = DBA::fetch($contacts)) {
1062 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1063 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1066 DBA::close($contacts);
1068 // The queries are split because of performance issues
1069 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1070 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1071 while ($contact = DBA::fetch($contacts)) {
1072 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1073 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1076 DBA::close($contacts);
1082 * Tests if the contact is a valid receiver for this actor
1084 * @param array $contact
1085 * @param array $tags
1087 * @return bool with receivers (user id)
1088 * @throws \Exception
1090 private static function isValidReceiverForActor(array $contact, array $tags): bool
1092 // Are we following the contact? Then this is a valid receiver
1093 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1097 // When the possible receiver isn't a community, then it is no valid receiver
1098 $owner = User::getOwnerDataById($contact['uid']);
1099 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1103 // Is the community account tagged?
1104 foreach ($tags as $tag) {
1105 if ($tag['type'] != 'Mention') {
1109 if (Strings::compareLink($tag['href'], $owner['url'])) {
1118 * Switches existing contacts to ActivityPub
1120 * @param integer $cid Contact ID
1121 * @param integer $uid User ID
1122 * @param string $url Profile URL
1124 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1125 * @throws \ImagickException
1127 public static function switchContact(int $cid, int $uid, string $url)
1129 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1130 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1134 if (Contact::updateFromProbe($cid)) {
1135 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1138 // Send a new follow request to be sure that the connection still exists
1139 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1140 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1141 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1146 * @TODO Fix documentation and type-hints
1151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1152 * @throws \ImagickException
1154 private static function switchContacts($receivers, $actor)
1156 if (empty($actor)) {
1160 foreach ($receivers as $receiver) {
1161 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1162 if (DBA::isResult($contact)) {
1163 self::switchContact($contact['id'], $receiver['uid'], $actor);
1166 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1167 if (DBA::isResult($contact)) {
1168 self::switchContact($contact['id'], $receiver['uid'], $actor);
1174 * @TODO Fix documentation and type-hints
1176 * @param $object_data
1177 * @param array $activity
1181 private static function addActivityFields($object_data, array $activity)
1183 if (!empty($activity['published']) && empty($object_data['published'])) {
1184 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1187 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1188 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1191 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1192 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1194 if (!empty($object_data['object_id'])) {
1195 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1196 $objectId = Item::getURIByLink($object_data['object_id']);
1197 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1198 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1199 $object_data['object_id'] = $objectId;
1203 return $object_data;
1207 * Fetches the object data from external ressources if needed
1209 * @param string $object_id Object ID of the the provided object
1210 * @param array $object The provided object array
1211 * @param boolean $trust_source Do we trust the provided object?
1212 * @param integer $uid User ID for the signature that we use to fetch data
1214 * @return array|false with trusted and valid object data
1215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1216 * @throws \ImagickException
1218 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1220 // By fetching the type we check if the object is complete.
1221 $type = JsonLD::fetchElement($object, '@type');
1223 if (!$trust_source || empty($type)) {
1224 $data = ActivityPub::fetchContent($object_id, $uid);
1225 if (!empty($data)) {
1226 $object = JsonLD::compact($data);
1227 Logger::info('Fetched content for ' . $object_id);
1229 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1231 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1232 if (!DBA::isResult($item)) {
1233 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1236 Logger::info('Using already stored item for url ' . $object_id);
1237 $data = ActivityPub\Transmitter::createNote($item);
1238 $object = JsonLD::compact($data);
1241 $id = JsonLD::fetchElement($object, '@id');
1243 Logger::info('Empty id');
1247 if ($id != $object_id) {
1248 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1252 Logger::info('Using original object for url ' . $object_id);
1255 $type = JsonLD::fetchElement($object, '@type');
1257 Logger::info('Empty type');
1261 // Lemmy is resharing "create" activities instead of content
1262 // We fetch the content from the activity.
1263 if (in_array($type, ['as:Create'])) {
1264 $object = $object['as:object'];
1265 $type = JsonLD::fetchElement($object, '@type');
1267 Logger::info('Empty type');
1270 $object_data = self::processObject($object);
1273 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1274 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1275 $object_data = self::processObject($object);
1277 if (!empty($data)) {
1278 $object_data['raw'] = json_encode($data);
1280 return $object_data;
1283 if ($type == 'as:Announce') {
1284 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1285 if (empty($object_id) || !is_string($object_id)) {
1288 return self::fetchObject($object_id, [], false, $uid);
1291 Logger::info('Unhandled object type: ' . $type);
1296 * Converts the language element (Used by Peertube)
1298 * @param array $languages
1299 * @return array Languages
1301 public static function processLanguages(array $languages): array
1303 if (empty($languages)) {
1307 $language_list = [];
1309 foreach ($languages as $language) {
1310 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1311 $language_list[$language['_:identifier']] = $language['as:name'];
1314 return $language_list;
1318 * Convert tags from JSON-LD format into a simplified format
1320 * @param array $tags Tags in JSON-LD format
1322 * @return array with tags in a simplified format
1324 public static function processTags(array $tags): array
1328 foreach ($tags as $tag) {
1333 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1334 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1335 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1337 if (empty($element['type'])) {
1341 if (empty($element['href'])) {
1342 $element['href'] = $element['name'];
1345 $taglist[] = $element;
1351 * Convert emojis from JSON-LD format into a simplified format
1353 * @param array $emojis
1354 * @return array with emojis in a simplified format
1356 private static function processEmojis(array $emojis): array
1360 foreach ($emojis as $emoji) {
1361 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1365 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1366 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1369 $emojilist[] = $element;
1376 * Convert attachments from JSON-LD format into a simplified format
1378 * @param array $attachments Attachments in JSON-LD format
1380 * @return array Attachments in a simplified format
1382 private static function processAttachments(array $attachments): array
1386 // Removes empty values
1387 $attachments = array_filter($attachments);
1389 foreach ($attachments as $attachment) {
1390 switch (JsonLD::fetchElement($attachment, '@type')) {
1395 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1396 foreach ($urls as $url) {
1397 // Single scalar URL case
1398 if (is_string($url)) {
1403 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1404 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1405 if (Strings::startsWith($mediaType, 'image')) {
1414 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1415 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1417 'image' => $pageImage,
1421 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1422 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1423 $imagePreviewUrl = null;
1425 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1426 $imageVariants = [];
1427 $previewVariants = [];
1428 foreach ($urls as $url) {
1429 // Scalar URL, no discrimination possible
1430 if (is_string($url)) {
1431 $imageFullUrl = $url;
1435 // Not sure what to do with a different Link media type than the base Image, we skip
1436 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1440 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1442 // Default URL choice if no discriminating width is provided
1443 $imageFullUrl = $href ?? $imageFullUrl;
1445 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1447 if ($href && $width) {
1448 $imageVariants[$width] = $href;
1449 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1450 $previewVariants[abs(632 - $width)] = $href;
1454 if ($imageVariants) {
1455 // Taking the maximum size image
1456 ksort($imageVariants);
1457 $imageFullUrl = array_pop($imageVariants);
1459 // Taking the minimum number distance to the target distance
1460 ksort($previewVariants);
1461 $imagePreviewUrl = array_shift($previewVariants);
1464 unset($imageVariants);
1465 unset($previewVariants);
1469 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1470 'mediaType' => $mediaType,
1471 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1472 'url' => $imageFullUrl,
1473 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1478 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1479 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1480 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1481 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1482 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1483 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1484 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1493 * Convert questions from JSON-LD format into a simplified format
1495 * @param array $object
1497 * @return array Questions in a simplified format
1499 private static function processQuestion(array $object): array
1503 if (!empty($object['as:oneOf'])) {
1504 $question['multiple'] = false;
1505 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1506 } elseif (!empty($object['as:anyOf'])) {
1507 $question['multiple'] = true;
1508 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1513 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1514 if (!empty($closed)) {
1515 $question['end-time'] = $closed;
1517 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1520 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1521 $question['options'] = [];
1525 foreach ($options as $option) {
1526 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1530 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1532 if (empty($option['as:replies'])) {
1536 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1538 $question['options'][] = ['name' => $name, 'replies' => $replies];
1540 $voters += (int)$replies;
1543 // For single choice question we can count the number of voters if not provided (like with Misskey)
1544 if (empty($question['voters']) && !$question['multiple']) {
1545 $question['voters'] = $voters;
1552 * Fetch the original source or content with the "language" Markdown or HTML
1554 * @param array $object
1555 * @param array $object_data
1557 * @return array Object data (?)
1558 * @throws \Exception
1560 private static function getSource(array $object, array $object_data): array
1562 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1563 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1564 if (!empty($object_data['source'])) {
1565 return $object_data;
1568 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1569 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1570 if (!empty($object_data['source'])) {
1571 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1572 return $object_data;
1575 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1576 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1577 if (!empty($object_data['source'])) {
1578 $object_data['source'] = HTML::toBBCode($object_data['source']);
1579 return $object_data;
1582 return $object_data;
1586 * Extracts a potential alternate URL from a list of additional URL elements
1588 * @param array $urls
1591 private static function extractAlternateUrl(array $urls): string
1594 foreach ($urls as $key => $url) {
1595 // Not a list but a single URL element
1596 if (!is_numeric($key)) {
1600 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1604 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1609 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1610 if (empty($mediatype)) {
1614 if ($mediatype == 'text/html') {
1615 $alternateUrl = $href;
1619 return $alternateUrl;
1623 * Check if the "as:url" element is an array with multiple links
1624 * This is the case with audio and video posts.
1625 * Then the links are added as attachments
1627 * @param array $urls The object URL list
1628 * @return array an array of attachments
1630 private static function processAttachmentUrls(array $urls): array
1633 foreach ($urls as $key => $url) {
1634 // Not a list but a single URL element
1635 if (!is_numeric($key)) {
1639 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1643 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1648 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1649 if (empty($mediatype)) {
1653 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1655 if ($filetype == 'audio') {
1656 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1657 } elseif ($filetype == 'video') {
1658 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1659 // PeerTube audio-only track
1660 if ($height === 0) {
1664 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1665 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1666 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1667 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1669 // For Torrent links we always store the highest resolution
1670 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1674 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1675 } elseif ($mediatype == 'application/x-mpegURL') {
1676 // PeerTube exception, actual video link is in the tags of this URL element
1677 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1681 return array_values($attachments);
1685 * Fetches data from the object part of an activity
1687 * @param array $object
1689 * @return array|bool Object data or FALSE if $object does not contain @id element
1690 * @throws \Exception
1692 private static function processObject(array $object)
1694 if (!JsonLD::fetchElement($object, '@id')) {
1699 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1700 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1701 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1703 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1704 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1705 $object_data['reply-to-id'] = $object_data['id'];
1707 // On activities the "reply to" is the id of the object it refers to
1708 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1709 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1710 if (!empty($object_id)) {
1711 $object_data['reply-to-id'] = $object_id;
1715 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1716 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1717 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1718 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1719 $object_data['reply-to-id'] = $replyToId;
1723 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1724 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1726 if (empty($object_data['updated'])) {
1727 $object_data['updated'] = $object_data['published'];
1730 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1731 $object_data['published'] = $object_data['updated'];
1734 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1735 if (empty($actor)) {
1736 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1739 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1740 $location = JsonLD::fetchElement($location, 'location', '@value');
1742 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1743 // down to HTML and then finally format to plaintext.
1744 $location = Markdown::convert($location);
1745 $location = BBCode::toPlaintext($location);
1748 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1749 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1750 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1751 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1752 $object_data['actor'] = $object_data['author'] = $actor;
1753 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1754 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1755 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1756 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1757 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1758 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1759 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1760 $object_data = self::getSource($object, $object_data);
1761 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1762 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1763 $object_data['location'] = $location;
1764 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1765 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1766 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1767 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1768 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1769 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1770 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1771 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1772 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1773 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1774 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1776 // Special treatment for Hubzilla links
1777 if (is_array($object_data['alternate-url'])) {
1778 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1780 if (!is_string($object_data['alternate-url'])) {
1781 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1785 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1786 $object_data['alternate-url'] = null;
1789 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1790 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1791 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1794 // For page types we expect that the alternate url posts to some page.
1795 // So we add this to the attachments if it differs from the id.
1796 // Currently only Lemmy is using the page type.
1797 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1798 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1799 $object_data['alternate-url'] = null;
1802 if ($object_data['object_type'] == 'as:Question') {
1803 $object_data['question'] = self::processQuestion($object);
1806 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1807 $receivers = $reception_types = [];
1808 foreach ($receiverdata as $key => $data) {
1809 $receivers[$key] = $data['uid'];
1810 $reception_types[$data['uid']] = $data['type'] ?? 0;
1813 $object_data['receiver_urls'] = self::getReceiverURL($object);
1814 $object_data['receiver'] = $receivers;
1815 $object_data['reception_type'] = $reception_types;
1817 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1818 unset($object_data['receiver'][-1]);
1819 unset($object_data['reception_type'][-1]);
1821 // Common object data:
1824 // @context, type, actor, signature, mediaType, duration, replies, icon
1826 // Also missing: (Defined in the standard, but currently unused)
1827 // audience, preview, endTime, startTime, image
1832 // contentMap, announcement_count, announcements, context_id, likes, like_count
1833 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1838 // category, licence, language, commentsEnabled
1841 // views, waitTranscoding, state, support, subtitleLanguage
1842 // likes, dislikes, shares, comments
1844 return $object_data;