3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
33 use Friendica\Model\Contact;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post;
37 use Friendica\Model\User;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\HTTPSignature;
42 use Friendica\Util\JsonLD;
43 use Friendica\Util\LDSignature;
44 use Friendica\Util\Network;
45 use Friendica\Util\Strings;
48 * ActivityPub Receiver Protocol class
53 * Check what this is meant to do:
62 const PUBLIC_COLLECTION = 'as:Public';
63 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
64 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
65 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
67 const TARGET_UNKNOWN = 0;
72 const TARGET_FOLLOWER = 5;
73 const TARGET_ANSWER = 6;
74 const TARGET_GLOBAL = 7;
76 const COMPLETION_NONE = 0;
77 const COMPLETION_ANNOUCE = 1;
78 const COMPLETION_RELAY = 2;
79 const COMPLETION_MANUAL = 3;
80 const COMPLETION_AUTO = 4;
83 * Checks incoming message from the inbox
85 * @param string $body Body string
86 * @param array $header Header lines
87 * @param integer $uid User ID
91 public static function processInbox(string $body, array $header, int $uid)
93 $activity = json_decode($body, true);
94 if (empty($activity)) {
95 Logger::warning('Invalid body.');
99 $ldactivity = JsonLD::compact($activity);
101 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
103 $apcontact = APContact::getByURL($actor);
105 if (empty($apcontact)) {
106 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
108 } elseif (APContact::isRelay($apcontact)) {
109 self::processRelayPost($ldactivity, $actor);
112 APContact::unmarkForArchival($apcontact);
115 $http_signer = HTTPSignature::getSigner($body, $header);
116 if ($http_signer === false) {
117 Logger::warning('Invalid HTTP signature, message will be discarded.');
119 } elseif (empty($http_signer)) {
120 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
123 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
126 $signer = [$http_signer];
128 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
130 if (LDSignature::isSigned($activity)) {
131 $ld_signer = LDSignature::getSigner($activity);
132 if (empty($ld_signer)) {
133 Logger::info('Invalid JSON-LD signature from ' . $actor);
134 } elseif ($ld_signer != $http_signer) {
135 $signer[] = $ld_signer;
137 if (!empty($ld_signer && ($actor == $http_signer))) {
138 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
139 $trust_source = true;
140 } elseif (!empty($ld_signer)) {
141 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
142 $trust_source = true;
143 } elseif ($actor == $http_signer) {
144 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
145 $trust_source = true;
147 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
148 $trust_source = false;
150 } elseif ($actor == $http_signer) {
151 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
152 $trust_source = true;
154 Logger::info('No JSON-LD signature, different actor.');
155 $trust_source = false;
158 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
162 * Process incoming posts from relays
164 * @param array $activity
165 * @param string $actor
168 private static function processRelayPost(array $activity, string $actor)
170 $type = JsonLD::fetchElement($activity, '@type');
172 Logger::info('Empty type', ['activity' => $activity, 'actor' => $actor]);
176 if ($type != 'as:Announce') {
177 Logger::info('Not an announcement', ['activity' => $activity, 'actor' => $actor]);
181 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
182 if (empty($object_id)) {
183 Logger::info('No object id found', ['activity' => $activity, 'actor' => $actor]);
187 $contact = Contact::getByURL($actor);
188 if (empty($contact)) {
189 Logger::info('Relay contact not found', ['actor' => $actor]);
193 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
194 Logger::notice('Relay is no sharer', ['actor' => $actor]);
198 Logger::info('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
200 $item_id = Item::searchByLink($object_id);
202 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
206 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
208 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
212 $item_id = Item::searchByLink($object_id);
214 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
216 Logger::notice('Relayed message had not been stored', ['id' => $object_id, 'actor' => $actor]);
221 * Fetches the object type for a given object id
223 * @param array $activity
224 * @param string $object_id Object ID of the the provided object
225 * @param integer $uid User ID
227 * @return string with object type or NULL
228 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
229 * @throws \ImagickException
231 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
233 if (!empty($activity['as:object'])) {
234 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
235 if (!empty($object_type)) {
240 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
241 // We just assume "note" since it doesn't make a difference for the further processing
245 $profile = APContact::getByURL($object_id);
246 if (!empty($profile['type'])) {
247 APContact::unmarkForArchival($profile);
248 return 'as:' . $profile['type'];
251 $data = ActivityPub::fetchContent($object_id, $uid);
253 $object = JsonLD::compact($data);
254 $type = JsonLD::fetchElement($object, '@type');
264 * Prepare the object array
266 * @param array $activity Array with activity data
267 * @param integer $uid User ID
268 * @param boolean $push Message had been pushed to our system
269 * @param boolean $trust_source Do we trust the source?
271 * @return array with object data
272 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
273 * @throws \ImagickException
275 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
277 $id = JsonLD::fetchElement($activity, '@id');
278 $type = JsonLD::fetchElement($activity, '@type');
279 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
281 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
282 $fetch_id = $object_id;
287 if (!empty($activity['as:object'])) {
288 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
291 if (!empty($id) && !$trust_source) {
292 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
294 $fetched_activity = ActivityPub::fetchContent($fetch_id, $fetch_uid);
295 if (!empty($fetched_activity)) {
296 $object = JsonLD::compact($fetched_activity);
298 $fetched_id = JsonLD::fetchElement($object, '@id');
299 $fetched_type = JsonLD::fetchElement($object, '@type');
301 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
302 Logger::info('Activity had been fetched successfully', ['id' => $id]);
303 $trust_source = true;
305 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
306 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
307 $trust_source = true;
308 unset($object['@context']);
309 $activity['as:object'] = $object;
311 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
314 Logger::info('Activity could not been fetched', ['id' => $id]);
318 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
320 Logger::info('Empty actor', ['activity' => $activity]);
324 $type = JsonLD::fetchElement($activity, '@type');
326 // Fetch all receivers from to, cc, bto and bcc
327 $receiverdata = self::getReceivers($activity, $actor);
328 $receivers = $reception_types = [];
329 foreach ($receiverdata as $key => $data) {
330 $receivers[$key] = $data['uid'];
331 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
334 $urls = self::getReceiverURL($activity);
336 // When it is a delivery to a personal inbox we add that user to the receivers
338 $additional = [$uid => $uid];
339 $receivers = array_replace($receivers, $additional);
340 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]))) {
341 $reception_types[$uid] = self::TARGET_BCC;
342 $owner = User::getOwnerDataById($uid);
343 if (!empty($owner['url'])) {
344 $urls['as:bcc'][] = $owner['url'];
349 // We possibly need some user to fetch private content,
350 // so we fetch one out of the receivers if no uid is provided.
351 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
353 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
354 if (empty($object_id)) {
355 Logger::info('No object found');
359 if (!is_string($object_id)) {
360 Logger::info('Invalid object id', ['object' => $object_id]);
364 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
366 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
367 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
368 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
370 $type = $object_type;
371 $activity = JsonLD::compact($data);
373 // Some variables need to be refetched since the activity changed
374 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
375 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
376 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
380 // Any activities on account types must not be altered
381 if (in_array($object_type, self::ACCOUNT_TYPES)) {
383 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
384 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
385 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
386 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
387 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
388 $object_data['push'] = $push;
389 if (!$trust_source && ($type == 'as:Delete')) {
390 $apcontact = APContact::getByURL($object_data['object_id'], true);
391 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
393 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
394 // Fetch the content only on activities where this matters
395 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
396 // Always fetch on "Announce"
397 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
398 if (empty($object_data)) {
399 Logger::info("Object data couldn't be processed");
403 $object_data['object_id'] = $object_id;
405 if ($type == 'as:Announce') {
406 $object_data['push'] = false;
408 $object_data['push'] = $push;
411 // Test if it is an answer to a mail
412 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
413 $object_data['directmessage'] = true;
415 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
417 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
418 // Create a mostly empty array out of the activity data (instead of the object).
419 // This way we later don't have to check for the existence of each individual array element.
420 $object_data = self::processObject($activity);
421 $object_data['name'] = $type;
422 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
423 $object_data['object_id'] = $object_id;
424 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
425 $object_data['push'] = $push;
426 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
428 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
429 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
430 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
431 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
432 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
433 $object_data['push'] = $push;
436 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
437 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
438 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
439 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
440 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
441 $object_data['push'] = $push;
443 // An Undo is done on the object of an object, so we need that type as well
444 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
445 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
448 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
449 $trust_source = Processor::isActivityGone($object_data['object_id']);
450 if (!$trust_source) {
451 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
456 $object_data = self::addActivityFields($object_data, $activity);
458 if (empty($object_data['object_type'])) {
459 $object_data['object_type'] = $object_type;
462 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
463 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
464 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
468 $object_data['type'] = $type;
469 $object_data['actor'] = $actor;
470 $object_data['item_receiver'] = $receivers;
471 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
472 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
474 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
475 // $author = $object_data['author'] ?? $actor;
476 // if (!empty($author) && !empty($object_data['id'])) {
477 // $author_host = parse_url($author, PHP_URL_HOST);
478 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
479 // if ($author_host == $id_host) {
480 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
482 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
483 // $trust_source = false;
487 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
493 * Fetches the first user id from the receiver array
495 * @param array $receivers Array with receivers
496 * @return integer user id;
498 public static function getFirstUserFromReceivers(array $receivers): int
500 foreach ($receivers as $receiver) {
501 if (!empty($receiver)) {
509 * Processes the activity object
511 * @param array $activity Array with activity data
512 * @param string $body The unprocessed body
513 * @param int|null $uid User ID
514 * @param boolean $trust_source Do we trust the source?
515 * @param boolean $push Message had been pushed to our system
516 * @param array $signer The signer of the post
517 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
518 * @throws \ImagickException
520 public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '')
522 $type = JsonLD::fetchElement($activity, '@type');
524 Logger::info('Empty type', ['activity' => $activity]);
528 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
529 Logger::info('Empty object', ['activity' => $activity]);
533 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
535 Logger::info('Empty actor', ['activity' => $activity]);
539 if (is_array($activity['as:object'])) {
540 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
545 // Test the provided signatures against the actor and "attributedTo"
547 if (!empty($attributed_to) && !empty($actor)) {
548 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
550 $trust_source = in_array($actor, $signer);
554 // $trust_source is called by reference and is set to true if the content was retrieved successfully
555 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
556 if (empty($object_data)) {
557 Logger::info('No object data found', ['activity' => $activity]);
561 // Lemmy is announcing activities.
562 // We are changing the announces into regular activities.
563 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
564 $type = $object_data['type'];
567 if (!empty($body) && empty($object_data['raw'])) {
568 $object_data['raw'] = $body;
571 // Internal flag for thread completion. See Processor.php
572 if (!empty($activity['thread-completion'])) {
573 $object_data['thread-completion'] = $activity['thread-completion'];
576 if (!empty($activity['completion-mode'])) {
577 $object_data['completion-mode'] = $activity['completion-mode'];
580 if (!empty($activity['thread-children-type'])) {
581 $object_data['thread-children-type'] = $activity['thread-children-type'];
584 // Internal flag for posts that arrived via relay
585 if (!empty($activity['from-relay'])) {
586 $object_data['from-relay'] = $activity['from-relay'];
589 if ($type == 'as:Announce') {
590 $object_data['object_activity'] = $activity;
593 if ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted')) {
594 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
597 if (!$trust_source) {
598 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
603 // We delay by 5 seconds to allow to accumulate all receivers
604 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
605 Worker::add(['priority' => PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
609 if (!empty($activity['recursion-depth'])) {
610 $object_data['recursion-depth'] = $activity['recursion-depth'];
613 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
614 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
617 if (!self::routeActivities($object_data, $type, $push)) {
618 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
619 Queue::remove($object_data);
626 * @param array $object_data
627 * @param string $type
628 * @param boolean $push
630 * @return boolean Could the activity be routed?
632 public static function routeActivities(array $object_data, string $type, bool $push): bool
634 $activity = $object_data['object_activity'] ?? [];
638 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
639 $item = ActivityPub\Processor::createItem($object_data);
640 ActivityPub\Processor::postItem($object_data, $item);
641 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
642 // Unhandled Peertube activity
643 Queue::remove($object_data);
650 if (in_array($object_data['object_type'], ['as:Event'])) {
651 $item = ActivityPub\Processor::createItem($object_data);
652 ActivityPub\Processor::postItem($object_data, $item);
659 if ($object_data['object_type'] == 'as:tag') {
660 ActivityPub\Processor::addTag($object_data);
661 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
662 ActivityPub\Processor::addToFeaturedCollection($object_data);
663 } elseif ($object_data['object_type'] == '') {
664 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
665 Queue::remove($object_data);
672 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
673 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
674 $object_data['thread-completion'] = Contact::getIdForURL($actor);
675 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
677 $item = ActivityPub\Processor::createItem($object_data);
682 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
683 ActivityPub\Processor::postItem($object_data, $item);
685 if (!empty($activity)) {
686 $announce_object_data = self::processObject($activity);
687 $announce_object_data['name'] = $type;
688 $announce_object_data['author'] = $actor;
689 $announce_object_data['object_id'] = $object_data['object_id'];
690 $announce_object_data['object_type'] = $object_data['object_type'];
691 $announce_object_data['push'] = $push;
693 if (!empty($object_data['raw'])) {
694 $announce_object_data['raw'] = $object_data['raw'];
696 if (!empty($object_data['raw-object'])) {
697 $announce_object_data['raw-object'] = $object_data['raw-object'];
699 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
707 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
708 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
709 } elseif ($object_data['object_type'] == '') {
710 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
711 Queue::remove($object_data);
718 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
719 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
720 } elseif ($object_data['object_type'] == '') {
721 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
722 Queue::remove($object_data);
728 case 'as:TentativeAccept':
729 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
730 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
737 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
738 ActivityPub\Processor::updateItem($object_data);
739 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
740 ActivityPub\Processor::updatePerson($object_data);
741 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
742 // Unhandled Peertube activity
743 Queue::remove($object_data);
750 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
751 ActivityPub\Processor::deleteItem($object_data);
752 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
753 ActivityPub\Processor::deletePerson($object_data);
754 } elseif ($object_data['object_type'] == '') {
755 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
756 Queue::remove($object_data);
763 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
764 ActivityPub\Processor::blockAccount($object_data);
771 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
772 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
773 } elseif ($object_data['object_type'] == '') {
774 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
775 Queue::remove($object_data);
782 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
783 ActivityPub\Processor::followUser($object_data);
784 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
785 $object_data['reply-to-id'] = $object_data['object_id'];
786 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
793 if ($object_data['object_type'] == 'as:Follow') {
794 ActivityPub\Processor::acceptFollowUser($object_data);
795 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
796 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
803 if ($object_data['object_type'] == 'as:Follow') {
804 ActivityPub\Processor::rejectFollowUser($object_data);
805 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
806 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
813 if (($object_data['object_type'] == 'as:Follow') &&
814 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
815 ActivityPub\Processor::undoFollowUser($object_data);
816 } elseif (($object_data['object_type'] == 'as:Follow') &&
817 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
818 ActivityPub\Processor::undoActivity($object_data);
819 } elseif (($object_data['object_type'] == 'as:Accept') &&
820 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
821 ActivityPub\Processor::rejectFollowUser($object_data);
822 } elseif (($object_data['object_type'] == 'as:Block') &&
823 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
824 ActivityPub\Processor::unblockAccount($object_data);
825 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
826 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
827 ActivityPub\Processor::undoActivity($object_data);
828 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
829 empty($object_data['object_object_type'])) {
830 // We cannot detect the target object. So we can ignore it.
831 Queue::remove($object_data);
832 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
833 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
834 // Unhandled Peertube activity
835 Queue::remove($object_data);
842 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
843 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
844 } elseif ($object_data['object_type'] == '') {
845 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
846 Queue::remove($object_data);
852 case 'litepub:EmojiReact':
853 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
854 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
855 } elseif ($object_data['object_type'] == '') {
856 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
857 Queue::remove($object_data);
864 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
871 * Stores unhandled or unknown Activities as a file
873 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
874 * @param string $type Activity type
875 * @param array $object_data Preprocessed array that is generated out of the received activity
876 * @param array $activity Array with activity data
877 * @param string $body The unprocessed body
878 * @param integer $uid User ID
879 * @param boolean $trust_source Do we trust the source?
880 * @param boolean $push Message had been pushed to our system
881 * @param array $signer The signer of the post
884 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 = [])
886 if (!DI::config()->get('debug', 'ap_log_unknown')) {
890 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
892 if (!empty($object_data['object_type'])) {
893 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
896 if (!empty($object_data['object_object_type'])) {
897 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
900 $tempfile = tempnam(System::getTempPath(), $file);
901 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));
902 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
906 * Fetch a user id from an activity array
908 * @param array $activity
909 * @param string $actor
911 * @return int user id
913 public static function getBestUserForActivity(array $activity): int
916 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
918 $receivers = self::getReceivers($activity, $actor);
919 foreach ($receivers as $receiver) {
920 if ($receiver['type'] == self::TARGET_GLOBAL) {
923 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
924 $uid = $receiver['uid'];
928 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
930 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
931 if (!empty($contact['uid'])) {
932 $uid = $contact['uid'];
939 // @TODO Missing documentation
940 public static function getReceiverURL(array $activity): array
944 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
945 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
946 if (empty($receiver_list)) {
950 foreach ($receiver_list as $receiver) {
951 if ($receiver == self::PUBLIC_COLLECTION) {
952 $receiver = ActivityPub::PUBLIC_COLLECTION;
954 $urls[$element][] = $receiver;
962 * Fetch the receiver list from an activity array
964 * @param array $activity
965 * @param string $actor
967 * @param boolean $fetch_unlisted
969 * @return array with receivers (user id)
972 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
974 $reply = $receivers = $profile = [];
976 // When it is an answer, we inherite the receivers from the parent
977 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
978 if (!empty($replyto)) {
981 // Fix possibly wrong item URI (could be an answer to a plink uri)
982 $fixedReplyTo = Item::getURIByLink($replyto);
983 if (!empty($fixedReplyTo)) {
984 $reply[] = $fixedReplyTo;
988 // Fetch all posts that refer to the object id
989 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
990 if (!empty($object_id)) {
991 $reply[] = $object_id;
994 if (!empty($reply)) {
995 $parents = Post::select(['uid'], ['uri' => $reply]);
996 while ($parent = Post::fetch($parents)) {
997 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
999 DBA::close($parents);
1002 if (!empty($actor)) {
1003 $profile = APContact::getByURL($actor);
1004 $followers = $profile['followers'] ?? '';
1005 $is_forum = ($actor['type'] ?? '') == 'Group';
1006 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1008 Logger::info('Empty actor', ['activity' => $activity]);
1013 // We have to prevent false follower assumptions upon thread completions
1014 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1016 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1017 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1018 if (empty($receiver_list)) {
1022 foreach ($receiver_list as $receiver) {
1023 if ($receiver == self::PUBLIC_COLLECTION) {
1024 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1027 // Add receiver "-1" for unlisted posts
1028 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1029 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1032 // Fetch the receivers for the public and the followers collection
1033 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1034 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1038 // Fetching all directly addressed receivers
1039 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1040 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1041 if (!DBA::isResult($contact)) {
1045 // Check if the potential receiver is following the actor
1046 // Exception: The receiver is targetted via "to" or this is a comment
1047 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1048 $networks = Protocol::FEDERATED;
1049 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1050 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1052 // Forum posts are only accepted from forum contacts
1053 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1054 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1057 if (!DBA::exists('contact', $condition)) {
1062 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1063 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1066 $type = self::TARGET_TO;
1069 $type = self::TARGET_CC;
1072 $type = self::TARGET_BTO;
1075 $type = self::TARGET_BCC;
1079 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1084 self::switchContacts($receivers, $actor);
1090 * Fetch the receiver list of a given actor
1092 * @param string $actor
1093 * @param array $tags
1094 * @param array $receivers
1095 * @param integer $target_type
1096 * @param array $profile
1098 * @return array with receivers (user id)
1099 * @throws \Exception
1101 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1103 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1104 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1106 if (!empty($profile['uri-id'])) {
1107 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1108 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1109 while ($contact = DBA::fetch($contacts)) {
1110 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1111 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1114 DBA::close($contacts);
1116 // This part will only be called while post update 1426 wasn't finished
1117 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1118 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1119 while ($contact = DBA::fetch($contacts)) {
1120 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1121 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1124 DBA::close($contacts);
1126 // The queries are split because of performance issues
1127 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1128 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1129 while ($contact = DBA::fetch($contacts)) {
1130 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1131 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1134 DBA::close($contacts);
1140 * Tests if the contact is a valid receiver for this actor
1142 * @param array $contact
1143 * @param array $tags
1145 * @return bool with receivers (user id)
1146 * @throws \Exception
1148 private static function isValidReceiverForActor(array $contact, array $tags): bool
1150 // Are we following the contact? Then this is a valid receiver
1151 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1155 // When the possible receiver isn't a community, then it is no valid receiver
1156 $owner = User::getOwnerDataById($contact['uid']);
1157 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1161 // Is the community account tagged?
1162 foreach ($tags as $tag) {
1163 if ($tag['type'] != 'Mention') {
1167 if (Strings::compareLink($tag['href'], $owner['url'])) {
1176 * Switches existing contacts to ActivityPub
1178 * @param integer $cid Contact ID
1179 * @param integer $uid User ID
1180 * @param string $url Profile URL
1182 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1183 * @throws \ImagickException
1185 public static function switchContact(int $cid, int $uid, string $url)
1187 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1188 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1192 if (Contact::updateFromProbe($cid)) {
1193 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1196 // Send a new follow request to be sure that the connection still exists
1197 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1198 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1199 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1204 * @TODO Fix documentation and type-hints
1209 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1210 * @throws \ImagickException
1212 private static function switchContacts($receivers, $actor)
1214 if (empty($actor)) {
1218 foreach ($receivers as $receiver) {
1219 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1220 if (DBA::isResult($contact)) {
1221 self::switchContact($contact['id'], $receiver['uid'], $actor);
1224 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1225 if (DBA::isResult($contact)) {
1226 self::switchContact($contact['id'], $receiver['uid'], $actor);
1232 * @TODO Fix documentation and type-hints
1234 * @param $object_data
1235 * @param array $activity
1239 private static function addActivityFields($object_data, array $activity)
1241 if (!empty($activity['published']) && empty($object_data['published'])) {
1242 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1245 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1246 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1249 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1250 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1252 if (!empty($object_data['object_id'])) {
1253 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1254 $objectId = Item::getURIByLink($object_data['object_id']);
1255 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1256 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1257 $object_data['object_id'] = $objectId;
1261 return $object_data;
1265 * Fetches the object data from external ressources if needed
1267 * @param string $object_id Object ID of the the provided object
1268 * @param array $object The provided object array
1269 * @param boolean $trust_source Do we trust the provided object?
1270 * @param integer $uid User ID for the signature that we use to fetch data
1272 * @return array|false with trusted and valid object data
1273 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1274 * @throws \ImagickException
1276 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1278 // By fetching the type we check if the object is complete.
1279 $type = JsonLD::fetchElement($object, '@type');
1281 if (!$trust_source || empty($type)) {
1282 $data = ActivityPub::fetchContent($object_id, $uid);
1283 if (!empty($data)) {
1284 $object = JsonLD::compact($data);
1285 Logger::info('Fetched content for ' . $object_id);
1287 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1289 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1290 if (!DBA::isResult($item)) {
1291 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1294 Logger::info('Using already stored item for url ' . $object_id);
1295 $data = ActivityPub\Transmitter::createNote($item);
1296 $object = JsonLD::compact($data);
1299 $id = JsonLD::fetchElement($object, '@id');
1301 Logger::info('Empty id');
1305 if ($id != $object_id) {
1306 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1310 Logger::info('Using original object for url ' . $object_id);
1313 $type = JsonLD::fetchElement($object, '@type');
1315 Logger::info('Empty type');
1319 // Lemmy is resharing "create" activities instead of content
1320 // We fetch the content from the activity.
1321 if (in_array($type, ['as:Create'])) {
1322 $object = $object['as:object'];
1323 $type = JsonLD::fetchElement($object, '@type');
1325 Logger::info('Empty type');
1328 $object_data = self::processObject($object);
1331 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1332 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1333 $object_data = self::processObject($object);
1335 if (!empty($data)) {
1336 $object_data['raw-object'] = json_encode($data);
1338 return $object_data;
1341 if ($type == 'as:Announce') {
1342 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1343 if (empty($object_id) || !is_string($object_id)) {
1346 return self::fetchObject($object_id, [], false, $uid);
1349 Logger::info('Unhandled object type: ' . $type);
1354 * Converts the language element (Used by Peertube)
1356 * @param array $languages
1357 * @return array Languages
1359 public static function processLanguages(array $languages): array
1361 if (empty($languages)) {
1365 $language_list = [];
1367 foreach ($languages as $language) {
1368 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1369 $language_list[$language['_:identifier']] = $language['as:name'];
1372 return $language_list;
1376 * Convert tags from JSON-LD format into a simplified format
1378 * @param array $tags Tags in JSON-LD format
1380 * @return array with tags in a simplified format
1382 public static function processTags(array $tags): array
1386 foreach ($tags as $tag) {
1391 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1392 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1393 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1395 if (empty($element['type'])) {
1399 if (empty($element['href'])) {
1400 $element['href'] = $element['name'];
1403 $taglist[] = $element;
1409 * Convert emojis from JSON-LD format into a simplified format
1411 * @param array $emojis
1412 * @return array with emojis in a simplified format
1414 private static function processEmojis(array $emojis): array
1418 foreach ($emojis as $emoji) {
1419 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1423 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1424 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1427 $emojilist[] = $element;
1434 * Convert attachments from JSON-LD format into a simplified format
1436 * @param array $attachments Attachments in JSON-LD format
1438 * @return array Attachments in a simplified format
1440 private static function processAttachments(array $attachments): array
1444 // Removes empty values
1445 $attachments = array_filter($attachments);
1447 foreach ($attachments as $attachment) {
1448 switch (JsonLD::fetchElement($attachment, '@type')) {
1453 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1454 foreach ($urls as $url) {
1455 // Single scalar URL case
1456 if (is_string($url)) {
1461 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1462 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1463 if (Strings::startsWith($mediaType, 'image')) {
1472 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1473 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1475 'image' => $pageImage,
1479 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1480 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1481 $imagePreviewUrl = null;
1483 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1484 $imageVariants = [];
1485 $previewVariants = [];
1486 foreach ($urls as $url) {
1487 // Scalar URL, no discrimination possible
1488 if (is_string($url)) {
1489 $imageFullUrl = $url;
1493 // Not sure what to do with a different Link media type than the base Image, we skip
1494 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1498 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1500 // Default URL choice if no discriminating width is provided
1501 $imageFullUrl = $href ?? $imageFullUrl;
1503 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1505 if ($href && $width) {
1506 $imageVariants[$width] = $href;
1507 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1508 $previewVariants[abs(632 - $width)] = $href;
1512 if ($imageVariants) {
1513 // Taking the maximum size image
1514 ksort($imageVariants);
1515 $imageFullUrl = array_pop($imageVariants);
1517 // Taking the minimum number distance to the target distance
1518 ksort($previewVariants);
1519 $imagePreviewUrl = array_shift($previewVariants);
1522 unset($imageVariants);
1523 unset($previewVariants);
1527 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1528 'mediaType' => $mediaType,
1529 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1530 'url' => $imageFullUrl,
1531 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1536 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1537 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1538 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1539 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1540 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1541 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1542 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1551 * Convert questions from JSON-LD format into a simplified format
1553 * @param array $object
1555 * @return array Questions in a simplified format
1557 private static function processQuestion(array $object): array
1561 if (!empty($object['as:oneOf'])) {
1562 $question['multiple'] = false;
1563 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1564 } elseif (!empty($object['as:anyOf'])) {
1565 $question['multiple'] = true;
1566 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1571 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1572 if (!empty($closed)) {
1573 $question['end-time'] = $closed;
1575 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1578 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1579 $question['options'] = [];
1583 foreach ($options as $option) {
1584 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1588 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1590 if (empty($option['as:replies'])) {
1594 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1596 $question['options'][] = ['name' => $name, 'replies' => $replies];
1598 $voters += (int)$replies;
1601 // For single choice question we can count the number of voters if not provided (like with Misskey)
1602 if (empty($question['voters']) && !$question['multiple']) {
1603 $question['voters'] = $voters;
1610 * Fetch the original source or content with the "language" Markdown or HTML
1612 * @param array $object
1613 * @param array $object_data
1615 * @return array Object data (?)
1616 * @throws \Exception
1618 private static function getSource(array $object, array $object_data): array
1620 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1621 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1622 if (!empty($object_data['source'])) {
1623 return $object_data;
1626 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1627 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1628 if (!empty($object_data['source'])) {
1629 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1630 return $object_data;
1633 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1634 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1635 if (!empty($object_data['source'])) {
1636 $object_data['source'] = HTML::toBBCode($object_data['source']);
1637 return $object_data;
1640 return $object_data;
1644 * Extracts a potential alternate URL from a list of additional URL elements
1646 * @param array $urls
1649 private static function extractAlternateUrl(array $urls): string
1652 foreach ($urls as $key => $url) {
1653 // Not a list but a single URL element
1654 if (!is_numeric($key)) {
1658 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1662 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1667 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1668 if (empty($mediatype)) {
1672 if ($mediatype == 'text/html') {
1673 $alternateUrl = $href;
1677 return $alternateUrl;
1681 * Check if the "as:url" element is an array with multiple links
1682 * This is the case with audio and video posts.
1683 * Then the links are added as attachments
1685 * @param array $urls The object URL list
1686 * @return array an array of attachments
1688 private static function processAttachmentUrls(array $urls): array
1691 foreach ($urls as $key => $url) {
1692 // Not a list but a single URL element
1693 if (!is_numeric($key)) {
1697 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1701 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1706 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1707 if (empty($mediatype)) {
1711 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1713 if ($filetype == 'audio') {
1714 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1715 } elseif ($filetype == 'video') {
1716 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1717 // PeerTube audio-only track
1718 if ($height === 0) {
1722 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1723 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1724 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1725 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1727 // For Torrent links we always store the highest resolution
1728 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1732 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1733 } elseif ($mediatype == 'application/x-mpegURL') {
1734 // PeerTube exception, actual video link is in the tags of this URL element
1735 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1739 return array_values($attachments);
1743 * Fetches data from the object part of an activity
1745 * @param array $object
1747 * @return array|bool Object data or FALSE if $object does not contain @id element
1748 * @throws \Exception
1750 private static function processObject(array $object)
1752 if (!JsonLD::fetchElement($object, '@id')) {
1757 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1758 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1759 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1761 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1762 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1763 $object_data['reply-to-id'] = $object_data['id'];
1765 // On activities the "reply to" is the id of the object it refers to
1766 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1767 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1768 if (!empty($object_id)) {
1769 $object_data['reply-to-id'] = $object_id;
1773 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1774 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1775 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1776 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1777 $object_data['reply-to-id'] = $replyToId;
1781 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1782 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1784 if (empty($object_data['updated'])) {
1785 $object_data['updated'] = $object_data['published'];
1788 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1789 $object_data['published'] = $object_data['updated'];
1792 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1793 if (empty($actor)) {
1794 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1797 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1798 $location = JsonLD::fetchElement($location, 'location', '@value');
1800 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1801 // down to HTML and then finally format to plaintext.
1802 $location = Markdown::convert($location);
1803 $location = BBCode::toPlaintext($location);
1806 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1807 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1808 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1809 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1810 $object_data['actor'] = $object_data['author'] = $actor;
1811 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1812 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1813 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1814 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1815 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1816 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1817 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1818 $object_data = self::getSource($object, $object_data);
1819 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1820 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1821 $object_data['location'] = $location;
1822 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1823 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1824 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1825 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1826 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1827 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1828 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1829 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1830 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1831 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1832 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1834 // Special treatment for Hubzilla links
1835 if (is_array($object_data['alternate-url'])) {
1836 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1838 if (!is_string($object_data['alternate-url'])) {
1839 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1843 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1844 $object_data['alternate-url'] = null;
1847 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1848 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1849 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1852 // For page types we expect that the alternate url posts to some page.
1853 // So we add this to the attachments if it differs from the id.
1854 // Currently only Lemmy is using the page type.
1855 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1856 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1857 $object_data['alternate-url'] = null;
1860 if ($object_data['object_type'] == 'as:Question') {
1861 $object_data['question'] = self::processQuestion($object);
1864 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1865 $receivers = $reception_types = [];
1866 foreach ($receiverdata as $key => $data) {
1867 $receivers[$key] = $data['uid'];
1868 $reception_types[$data['uid']] = $data['type'] ?? 0;
1871 $object_data['receiver_urls'] = self::getReceiverURL($object);
1872 $object_data['receiver'] = $receivers;
1873 $object_data['reception_type'] = $reception_types;
1875 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1876 unset($object_data['receiver'][-1]);
1877 unset($object_data['reception_type'][-1]);
1879 return $object_data;