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 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
278 if (!empty($id) && !$trust_source) {
279 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
281 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
282 if (!empty($fetched_activity)) {
283 $object = JsonLD::compact($fetched_activity);
284 $fetched_id = JsonLD::fetchElement($object, '@id');
285 if ($fetched_id == $id) {
286 Logger::info('Activity had been fetched successfully', ['id' => $id]);
287 $trust_source = true;
288 if ($id != $object_id) {
291 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
292 unset($object['@context']);
293 $activity['as:object'] = $object;
296 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
299 Logger::info('Activity could not been fetched', ['id' => $id]);
303 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
305 Logger::info('Empty actor', ['activity' => $activity]);
309 $type = JsonLD::fetchElement($activity, '@type');
311 // Fetch all receivers from to, cc, bto and bcc
312 $receiverdata = self::getReceivers($activity, $actor);
313 $receivers = $reception_types = [];
314 foreach ($receiverdata as $key => $data) {
315 $receivers[$key] = $data['uid'];
316 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
319 $urls = self::getReceiverURL($activity);
321 // When it is a delivery to a personal inbox we add that user to the receivers
323 $additional = [$uid => $uid];
324 $receivers = array_replace($receivers, $additional);
325 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]))) {
326 $reception_types[$uid] = self::TARGET_BCC;
327 $owner = User::getOwnerDataById($uid);
328 if (!empty($owner['url'])) {
329 $urls['as:bcc'][] = $owner['url'];
334 // We possibly need some user to fetch private content,
335 // so we fetch one out of the receivers if no uid is provided.
336 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
338 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
339 if (empty($object_id)) {
340 Logger::info('No object found');
344 if (!is_string($object_id)) {
345 Logger::info('Invalid object id', ['object' => $object_id]);
349 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
351 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
352 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
353 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
355 $type = $object_type;
356 $activity = JsonLD::compact($data);
358 // Some variables need to be refetched since the activity changed
359 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
360 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
361 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
365 // Any activities on account types must not be altered
366 if (in_array($object_type, self::ACCOUNT_TYPES)) {
368 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
369 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
370 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
371 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
372 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
373 $object_data['push'] = $push;
374 if ($type == 'as:Delete') {
375 $apcontact = APContact::getByURL($object_data['object_id'], true);
376 $trust_source = ($apcontact['type'] == 'Tombstone');
378 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
379 // Fetch the content only on activities where this matters
380 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
381 // Always fetch on "Announce"
382 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
383 if (empty($object_data)) {
384 Logger::info("Object data couldn't be processed");
388 $object_data['object_id'] = $object_id;
390 if ($type == 'as:Announce') {
391 $object_data['push'] = false;
393 $object_data['push'] = $push;
396 // Test if it is an answer to a mail
397 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
398 $object_data['directmessage'] = true;
400 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
402 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
403 // Create a mostly empty array out of the activity data (instead of the object).
404 // This way we later don't have to check for the existence of each individual array element.
405 $object_data = self::processObject($activity);
406 $object_data['name'] = $type;
407 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
408 $object_data['object_id'] = $object_id;
409 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
410 $object_data['push'] = $push;
411 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
413 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
414 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
415 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
416 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
417 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
418 $object_data['push'] = $push;
421 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
422 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
423 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
424 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
425 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
426 $object_data['push'] = $push;
428 // An Undo is done on the object of an object, so we need that type as well
429 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
430 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
433 if (($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
434 $trust_source = Processor::isActivityGone($object_data['object_id']);
438 $object_data = self::addActivityFields($object_data, $activity);
440 if (empty($object_data['object_type'])) {
441 $object_data['object_type'] = $object_type;
444 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
445 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
446 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
450 $object_data['type'] = $type;
451 $object_data['actor'] = $actor;
452 $object_data['item_receiver'] = $receivers;
453 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
454 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
456 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
457 // $author = $object_data['author'] ?? $actor;
458 // if (!empty($author) && !empty($object_data['id'])) {
459 // $author_host = parse_url($author, PHP_URL_HOST);
460 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
461 // if ($author_host == $id_host) {
462 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
464 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
465 // $trust_source = false;
469 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
475 * Fetches the first user id from the receiver array
477 * @param array $receivers Array with receivers
478 * @return integer user id;
480 public static function getFirstUserFromReceivers(array $receivers): int
482 foreach ($receivers as $receiver) {
483 if (!empty($receiver)) {
491 * Processes the activity object
493 * @param array $activity Array with activity data
494 * @param string $body The unprocessed body
495 * @param int|null $uid User ID
496 * @param boolean $trust_source Do we trust the source?
497 * @param boolean $push Message had been pushed to our system
498 * @param array $signer The signer of the post
499 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
500 * @throws \ImagickException
502 public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '')
504 $type = JsonLD::fetchElement($activity, '@type');
506 Logger::info('Empty type', ['activity' => $activity]);
510 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
511 Logger::info('Empty object', ['activity' => $activity]);
515 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
517 Logger::info('Empty actor', ['activity' => $activity]);
521 if (is_array($activity['as:object'])) {
522 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
527 // Test the provided signatures against the actor and "attributedTo"
529 if (!empty($attributed_to) && !empty($actor)) {
530 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
532 $trust_source = in_array($actor, $signer);
536 // $trust_source is called by reference and is set to true if the content was retrieved successfully
537 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
538 if (empty($object_data)) {
539 Logger::info('No object data found', ['activity' => $activity]);
543 // Lemmy is announcing activities.
544 // We are changing the announces into regular activities.
545 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
546 $type = $object_data['type'];
549 if (!empty($body) && empty($object_data['raw'])) {
550 $object_data['raw'] = $body;
553 // Internal flag for thread completion. See Processor.php
554 if (!empty($activity['thread-completion'])) {
555 $object_data['thread-completion'] = $activity['thread-completion'];
558 if (!empty($activity['completion-mode'])) {
559 $object_data['completion-mode'] = $activity['completion-mode'];
562 if (!empty($activity['thread-children-type'])) {
563 $object_data['thread-children-type'] = $activity['thread-children-type'];
566 // Internal flag for posts that arrived via relay
567 if (!empty($activity['from-relay'])) {
568 $object_data['from-relay'] = $activity['from-relay'];
571 if ($type == 'as:Announce') {
572 $object_data['object_activity'] = $activity;
575 if ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted')) {
576 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
579 if (!$trust_source) {
580 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
584 if (!empty($activity['recursion-depth'])) {
585 $object_data['recursion-depth'] = $activity['recursion-depth'];
588 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
589 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
592 if (!self::routeActivities($object_data, $type, $push)) {
593 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
594 Queue::remove($object_data);
601 * @param array $object_data
602 * @param string $type
603 * @param boolean $push
605 * @return boolean Could the activity be routed?
607 public static function routeActivities(array $object_data, string $type, bool $push): bool
609 $activity = $object_data['object_activity'] ?? [];
613 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
614 $item = ActivityPub\Processor::createItem($object_data);
615 ActivityPub\Processor::postItem($object_data, $item);
616 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
617 // Unhandled Peertube activity
618 Queue::remove($object_data);
625 if (in_array($object_data['object_type'], ['as:Event'])) {
626 $item = ActivityPub\Processor::createItem($object_data);
627 ActivityPub\Processor::postItem($object_data, $item);
634 if ($object_data['object_type'] == 'as:tag') {
635 ActivityPub\Processor::addTag($object_data);
636 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
637 ActivityPub\Processor::addToFeaturedCollection($object_data);
638 } elseif ($object_data['object_type'] == '') {
639 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
640 Queue::remove($object_data);
647 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
648 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
649 $object_data['thread-completion'] = Contact::getIdForURL($actor);
650 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
652 $item = ActivityPub\Processor::createItem($object_data);
657 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
658 ActivityPub\Processor::postItem($object_data, $item);
660 if (!empty($activity)) {
661 $announce_object_data = self::processObject($activity);
662 $announce_object_data['name'] = $type;
663 $announce_object_data['author'] = $actor;
664 $announce_object_data['object_id'] = $object_data['object_id'];
665 $announce_object_data['object_type'] = $object_data['object_type'];
666 $announce_object_data['push'] = $push;
668 if (!empty($object_data['raw'])) {
669 $announce_object_data['raw'] = $object_data['raw'];
671 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
679 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
680 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
681 } elseif ($object_data['object_type'] == '') {
682 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
683 Queue::remove($object_data);
690 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
691 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
692 } elseif ($object_data['object_type'] == '') {
693 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
694 Queue::remove($object_data);
700 case 'as:TentativeAccept':
701 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
702 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
709 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
710 ActivityPub\Processor::updateItem($object_data);
711 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
712 ActivityPub\Processor::updatePerson($object_data);
713 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
714 // Unhandled Peertube activity
715 Queue::remove($object_data);
722 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
723 ActivityPub\Processor::deleteItem($object_data);
724 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
725 ActivityPub\Processor::deletePerson($object_data);
726 } elseif ($object_data['object_type'] == '') {
727 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
728 Queue::remove($object_data);
735 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
736 ActivityPub\Processor::blockAccount($object_data);
743 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
744 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
745 } elseif ($object_data['object_type'] == '') {
746 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
747 Queue::remove($object_data);
754 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
755 ActivityPub\Processor::followUser($object_data);
756 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
757 $object_data['reply-to-id'] = $object_data['object_id'];
758 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
765 if ($object_data['object_type'] == 'as:Follow') {
766 ActivityPub\Processor::acceptFollowUser($object_data);
767 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
768 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
775 if ($object_data['object_type'] == 'as:Follow') {
776 ActivityPub\Processor::rejectFollowUser($object_data);
777 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
778 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
785 if (($object_data['object_type'] == 'as:Follow') &&
786 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
787 ActivityPub\Processor::undoFollowUser($object_data);
788 } elseif (($object_data['object_type'] == 'as:Follow') &&
789 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
790 ActivityPub\Processor::undoActivity($object_data);
791 } elseif (($object_data['object_type'] == 'as:Accept') &&
792 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
793 ActivityPub\Processor::rejectFollowUser($object_data);
794 } elseif (($object_data['object_type'] == 'as:Block') &&
795 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
796 ActivityPub\Processor::unblockAccount($object_data);
797 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
798 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
799 ActivityPub\Processor::undoActivity($object_data);
800 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
801 empty($object_data['object_object_type'])) {
802 // We cannot detect the target object. So we can ignore it.
803 Queue::remove($object_data);
804 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
805 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
806 // Unhandled Peertube activity
807 Queue::remove($object_data);
814 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
815 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
816 } elseif ($object_data['object_type'] == '') {
817 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
818 Queue::remove($object_data);
824 case 'litepub:EmojiReact':
825 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
826 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
827 } elseif ($object_data['object_type'] == '') {
828 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
829 Queue::remove($object_data);
836 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
843 * Stores unhandled or unknown Activities as a file
845 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
846 * @param string $type Activity type
847 * @param array $object_data Preprocessed array that is generated out of the received activity
848 * @param array $activity Array with activity data
849 * @param string $body The unprocessed body
850 * @param integer $uid User ID
851 * @param boolean $trust_source Do we trust the source?
852 * @param boolean $push Message had been pushed to our system
853 * @param array $signer The signer of the post
856 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 = [])
858 if (!DI::config()->get('debug', 'ap_log_unknown')) {
862 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
864 if (!empty($object_data['object_type'])) {
865 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
868 if (!empty($object_data['object_object_type'])) {
869 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
872 $tempfile = tempnam(System::getTempPath(), $file);
873 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));
874 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
878 * Fetch a user id from an activity array
880 * @param array $activity
881 * @param string $actor
883 * @return int user id
885 public static function getBestUserForActivity(array $activity): int
888 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
890 $receivers = self::getReceivers($activity, $actor);
891 foreach ($receivers as $receiver) {
892 if ($receiver['type'] == self::TARGET_GLOBAL) {
895 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
896 $uid = $receiver['uid'];
900 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
902 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
903 if (!empty($contact['uid'])) {
904 $uid = $contact['uid'];
911 // @TODO Missing documentation
912 public static function getReceiverURL(array $activity): array
916 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
917 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
918 if (empty($receiver_list)) {
922 foreach ($receiver_list as $receiver) {
923 if ($receiver == self::PUBLIC_COLLECTION) {
924 $receiver = ActivityPub::PUBLIC_COLLECTION;
926 $urls[$element][] = $receiver;
934 * Fetch the receiver list from an activity array
936 * @param array $activity
937 * @param string $actor
939 * @param boolean $fetch_unlisted
941 * @return array with receivers (user id)
944 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
946 $reply = $receivers = $profile = [];
948 // When it is an answer, we inherite the receivers from the parent
949 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
950 if (!empty($replyto)) {
953 // Fix possibly wrong item URI (could be an answer to a plink uri)
954 $fixedReplyTo = Item::getURIByLink($replyto);
955 if (!empty($fixedReplyTo)) {
956 $reply[] = $fixedReplyTo;
960 // Fetch all posts that refer to the object id
961 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
962 if (!empty($object_id)) {
963 $reply[] = $object_id;
966 if (!empty($reply)) {
967 $parents = Post::select(['uid'], ['uri' => $reply]);
968 while ($parent = Post::fetch($parents)) {
969 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
971 DBA::close($parents);
974 if (!empty($actor)) {
975 $profile = APContact::getByURL($actor);
976 $followers = $profile['followers'] ?? '';
977 $is_forum = ($actor['type'] ?? '') == 'Group';
978 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
980 Logger::info('Empty actor', ['activity' => $activity]);
985 // We have to prevent false follower assumptions upon thread completions
986 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
988 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
989 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
990 if (empty($receiver_list)) {
994 foreach ($receiver_list as $receiver) {
995 if ($receiver == self::PUBLIC_COLLECTION) {
996 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
999 // Add receiver "-1" for unlisted posts
1000 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1001 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1004 // Fetch the receivers for the public and the followers collection
1005 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1006 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1010 // Fetching all directly addressed receivers
1011 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1012 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1013 if (!DBA::isResult($contact)) {
1017 // Check if the potential receiver is following the actor
1018 // Exception: The receiver is targetted via "to" or this is a comment
1019 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1020 $networks = Protocol::FEDERATED;
1021 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1022 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1024 // Forum posts are only accepted from forum contacts
1025 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1026 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1029 if (!DBA::exists('contact', $condition)) {
1034 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1035 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1038 $type = self::TARGET_TO;
1041 $type = self::TARGET_CC;
1044 $type = self::TARGET_BTO;
1047 $type = self::TARGET_BCC;
1051 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1056 self::switchContacts($receivers, $actor);
1062 * Fetch the receiver list of a given actor
1064 * @param string $actor
1065 * @param array $tags
1066 * @param array $receivers
1067 * @param integer $target_type
1068 * @param array $profile
1070 * @return array with receivers (user id)
1071 * @throws \Exception
1073 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1075 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1076 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1078 if (!empty($profile['uri-id'])) {
1079 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1080 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1081 while ($contact = DBA::fetch($contacts)) {
1082 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1083 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1086 DBA::close($contacts);
1088 // This part will only be called while post update 1426 wasn't finished
1089 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1090 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1091 while ($contact = DBA::fetch($contacts)) {
1092 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1093 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1096 DBA::close($contacts);
1098 // The queries are split because of performance issues
1099 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1100 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1101 while ($contact = DBA::fetch($contacts)) {
1102 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1103 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1106 DBA::close($contacts);
1112 * Tests if the contact is a valid receiver for this actor
1114 * @param array $contact
1115 * @param array $tags
1117 * @return bool with receivers (user id)
1118 * @throws \Exception
1120 private static function isValidReceiverForActor(array $contact, array $tags): bool
1122 // Are we following the contact? Then this is a valid receiver
1123 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1127 // When the possible receiver isn't a community, then it is no valid receiver
1128 $owner = User::getOwnerDataById($contact['uid']);
1129 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1133 // Is the community account tagged?
1134 foreach ($tags as $tag) {
1135 if ($tag['type'] != 'Mention') {
1139 if (Strings::compareLink($tag['href'], $owner['url'])) {
1148 * Switches existing contacts to ActivityPub
1150 * @param integer $cid Contact ID
1151 * @param integer $uid User ID
1152 * @param string $url Profile URL
1154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1155 * @throws \ImagickException
1157 public static function switchContact(int $cid, int $uid, string $url)
1159 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1160 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1164 if (Contact::updateFromProbe($cid)) {
1165 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1168 // Send a new follow request to be sure that the connection still exists
1169 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1170 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1171 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1176 * @TODO Fix documentation and type-hints
1181 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1182 * @throws \ImagickException
1184 private static function switchContacts($receivers, $actor)
1186 if (empty($actor)) {
1190 foreach ($receivers as $receiver) {
1191 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1192 if (DBA::isResult($contact)) {
1193 self::switchContact($contact['id'], $receiver['uid'], $actor);
1196 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1197 if (DBA::isResult($contact)) {
1198 self::switchContact($contact['id'], $receiver['uid'], $actor);
1204 * @TODO Fix documentation and type-hints
1206 * @param $object_data
1207 * @param array $activity
1211 private static function addActivityFields($object_data, array $activity)
1213 if (!empty($activity['published']) && empty($object_data['published'])) {
1214 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1217 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1218 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1221 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1222 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1224 if (!empty($object_data['object_id'])) {
1225 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1226 $objectId = Item::getURIByLink($object_data['object_id']);
1227 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1228 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1229 $object_data['object_id'] = $objectId;
1233 return $object_data;
1237 * Fetches the object data from external ressources if needed
1239 * @param string $object_id Object ID of the the provided object
1240 * @param array $object The provided object array
1241 * @param boolean $trust_source Do we trust the provided object?
1242 * @param integer $uid User ID for the signature that we use to fetch data
1244 * @return array|false with trusted and valid object data
1245 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1246 * @throws \ImagickException
1248 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1250 // By fetching the type we check if the object is complete.
1251 $type = JsonLD::fetchElement($object, '@type');
1253 if (!$trust_source || empty($type)) {
1254 $data = ActivityPub::fetchContent($object_id, $uid);
1255 if (!empty($data)) {
1256 $object = JsonLD::compact($data);
1257 Logger::info('Fetched content for ' . $object_id);
1259 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1261 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1262 if (!DBA::isResult($item)) {
1263 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1266 Logger::info('Using already stored item for url ' . $object_id);
1267 $data = ActivityPub\Transmitter::createNote($item);
1268 $object = JsonLD::compact($data);
1271 $id = JsonLD::fetchElement($object, '@id');
1273 Logger::info('Empty id');
1277 if ($id != $object_id) {
1278 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1282 Logger::info('Using original object for url ' . $object_id);
1285 $type = JsonLD::fetchElement($object, '@type');
1287 Logger::info('Empty type');
1291 // Lemmy is resharing "create" activities instead of content
1292 // We fetch the content from the activity.
1293 if (in_array($type, ['as:Create'])) {
1294 $object = $object['as:object'];
1295 $type = JsonLD::fetchElement($object, '@type');
1297 Logger::info('Empty type');
1300 $object_data = self::processObject($object);
1303 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1304 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1305 $object_data = self::processObject($object);
1307 if (!empty($data)) {
1308 $object_data['raw'] = json_encode($data);
1310 return $object_data;
1313 if ($type == 'as:Announce') {
1314 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1315 if (empty($object_id) || !is_string($object_id)) {
1318 return self::fetchObject($object_id, [], false, $uid);
1321 Logger::info('Unhandled object type: ' . $type);
1326 * Converts the language element (Used by Peertube)
1328 * @param array $languages
1329 * @return array Languages
1331 public static function processLanguages(array $languages): array
1333 if (empty($languages)) {
1337 $language_list = [];
1339 foreach ($languages as $language) {
1340 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1341 $language_list[$language['_:identifier']] = $language['as:name'];
1344 return $language_list;
1348 * Convert tags from JSON-LD format into a simplified format
1350 * @param array $tags Tags in JSON-LD format
1352 * @return array with tags in a simplified format
1354 public static function processTags(array $tags): array
1358 foreach ($tags as $tag) {
1363 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1364 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1365 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1367 if (empty($element['type'])) {
1371 if (empty($element['href'])) {
1372 $element['href'] = $element['name'];
1375 $taglist[] = $element;
1381 * Convert emojis from JSON-LD format into a simplified format
1383 * @param array $emojis
1384 * @return array with emojis in a simplified format
1386 private static function processEmojis(array $emojis): array
1390 foreach ($emojis as $emoji) {
1391 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1395 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1396 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1399 $emojilist[] = $element;
1406 * Convert attachments from JSON-LD format into a simplified format
1408 * @param array $attachments Attachments in JSON-LD format
1410 * @return array Attachments in a simplified format
1412 private static function processAttachments(array $attachments): array
1416 // Removes empty values
1417 $attachments = array_filter($attachments);
1419 foreach ($attachments as $attachment) {
1420 switch (JsonLD::fetchElement($attachment, '@type')) {
1425 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1426 foreach ($urls as $url) {
1427 // Single scalar URL case
1428 if (is_string($url)) {
1433 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1434 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1435 if (Strings::startsWith($mediaType, 'image')) {
1444 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1445 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1447 'image' => $pageImage,
1451 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1452 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1453 $imagePreviewUrl = null;
1455 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1456 $imageVariants = [];
1457 $previewVariants = [];
1458 foreach ($urls as $url) {
1459 // Scalar URL, no discrimination possible
1460 if (is_string($url)) {
1461 $imageFullUrl = $url;
1465 // Not sure what to do with a different Link media type than the base Image, we skip
1466 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1470 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1472 // Default URL choice if no discriminating width is provided
1473 $imageFullUrl = $href ?? $imageFullUrl;
1475 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1477 if ($href && $width) {
1478 $imageVariants[$width] = $href;
1479 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1480 $previewVariants[abs(632 - $width)] = $href;
1484 if ($imageVariants) {
1485 // Taking the maximum size image
1486 ksort($imageVariants);
1487 $imageFullUrl = array_pop($imageVariants);
1489 // Taking the minimum number distance to the target distance
1490 ksort($previewVariants);
1491 $imagePreviewUrl = array_shift($previewVariants);
1494 unset($imageVariants);
1495 unset($previewVariants);
1499 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1500 'mediaType' => $mediaType,
1501 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1502 'url' => $imageFullUrl,
1503 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1508 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1509 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1510 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1511 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1512 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1513 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1514 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1523 * Convert questions from JSON-LD format into a simplified format
1525 * @param array $object
1527 * @return array Questions in a simplified format
1529 private static function processQuestion(array $object): array
1533 if (!empty($object['as:oneOf'])) {
1534 $question['multiple'] = false;
1535 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1536 } elseif (!empty($object['as:anyOf'])) {
1537 $question['multiple'] = true;
1538 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1543 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1544 if (!empty($closed)) {
1545 $question['end-time'] = $closed;
1547 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1550 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1551 $question['options'] = [];
1555 foreach ($options as $option) {
1556 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1560 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1562 if (empty($option['as:replies'])) {
1566 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1568 $question['options'][] = ['name' => $name, 'replies' => $replies];
1570 $voters += (int)$replies;
1573 // For single choice question we can count the number of voters if not provided (like with Misskey)
1574 if (empty($question['voters']) && !$question['multiple']) {
1575 $question['voters'] = $voters;
1582 * Fetch the original source or content with the "language" Markdown or HTML
1584 * @param array $object
1585 * @param array $object_data
1587 * @return array Object data (?)
1588 * @throws \Exception
1590 private static function getSource(array $object, array $object_data): array
1592 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1593 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1594 if (!empty($object_data['source'])) {
1595 return $object_data;
1598 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1599 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1600 if (!empty($object_data['source'])) {
1601 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1602 return $object_data;
1605 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1606 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1607 if (!empty($object_data['source'])) {
1608 $object_data['source'] = HTML::toBBCode($object_data['source']);
1609 return $object_data;
1612 return $object_data;
1616 * Extracts a potential alternate URL from a list of additional URL elements
1618 * @param array $urls
1621 private static function extractAlternateUrl(array $urls): string
1624 foreach ($urls as $key => $url) {
1625 // Not a list but a single URL element
1626 if (!is_numeric($key)) {
1630 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1634 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1639 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1640 if (empty($mediatype)) {
1644 if ($mediatype == 'text/html') {
1645 $alternateUrl = $href;
1649 return $alternateUrl;
1653 * Check if the "as:url" element is an array with multiple links
1654 * This is the case with audio and video posts.
1655 * Then the links are added as attachments
1657 * @param array $urls The object URL list
1658 * @return array an array of attachments
1660 private static function processAttachmentUrls(array $urls): array
1663 foreach ($urls as $key => $url) {
1664 // Not a list but a single URL element
1665 if (!is_numeric($key)) {
1669 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1673 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1678 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1679 if (empty($mediatype)) {
1683 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1685 if ($filetype == 'audio') {
1686 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1687 } elseif ($filetype == 'video') {
1688 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1689 // PeerTube audio-only track
1690 if ($height === 0) {
1694 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1695 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1696 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1697 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1699 // For Torrent links we always store the highest resolution
1700 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1704 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1705 } elseif ($mediatype == 'application/x-mpegURL') {
1706 // PeerTube exception, actual video link is in the tags of this URL element
1707 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1711 return array_values($attachments);
1715 * Fetches data from the object part of an activity
1717 * @param array $object
1719 * @return array|bool Object data or FALSE if $object does not contain @id element
1720 * @throws \Exception
1722 private static function processObject(array $object)
1724 if (!JsonLD::fetchElement($object, '@id')) {
1729 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1730 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1731 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1733 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1734 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1735 $object_data['reply-to-id'] = $object_data['id'];
1737 // On activities the "reply to" is the id of the object it refers to
1738 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1739 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1740 if (!empty($object_id)) {
1741 $object_data['reply-to-id'] = $object_id;
1745 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1746 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1747 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1748 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1749 $object_data['reply-to-id'] = $replyToId;
1753 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1754 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1756 if (empty($object_data['updated'])) {
1757 $object_data['updated'] = $object_data['published'];
1760 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1761 $object_data['published'] = $object_data['updated'];
1764 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1765 if (empty($actor)) {
1766 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1769 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1770 $location = JsonLD::fetchElement($location, 'location', '@value');
1772 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1773 // down to HTML and then finally format to plaintext.
1774 $location = Markdown::convert($location);
1775 $location = BBCode::toPlaintext($location);
1778 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1779 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1780 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1781 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1782 $object_data['actor'] = $object_data['author'] = $actor;
1783 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1784 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1785 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1786 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1787 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1788 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1789 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1790 $object_data = self::getSource($object, $object_data);
1791 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1792 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1793 $object_data['location'] = $location;
1794 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1795 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1796 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1797 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1798 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1799 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1800 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1801 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1802 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1803 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1804 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1806 // Special treatment for Hubzilla links
1807 if (is_array($object_data['alternate-url'])) {
1808 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1810 if (!is_string($object_data['alternate-url'])) {
1811 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1815 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1816 $object_data['alternate-url'] = null;
1819 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1820 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1821 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1824 // For page types we expect that the alternate url posts to some page.
1825 // So we add this to the attachments if it differs from the id.
1826 // Currently only Lemmy is using the page type.
1827 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1828 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1829 $object_data['alternate-url'] = null;
1832 if ($object_data['object_type'] == 'as:Question') {
1833 $object_data['question'] = self::processQuestion($object);
1836 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1837 $receivers = $reception_types = [];
1838 foreach ($receiverdata as $key => $data) {
1839 $receivers[$key] = $data['uid'];
1840 $reception_types[$data['uid']] = $data['type'] ?? 0;
1843 $object_data['receiver_urls'] = self::getReceiverURL($object);
1844 $object_data['receiver'] = $receivers;
1845 $object_data['reception_type'] = $reception_types;
1847 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1848 unset($object_data['receiver'][-1]);
1849 unset($object_data['reception_type'][-1]);
1851 return $object_data;