3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
32 use Friendica\Model\Contact;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Util\HTTPSignature;
40 use Friendica\Util\JsonLD;
41 use Friendica\Util\LDSignature;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
46 * ActivityPub Receiver Protocol class
51 * Check what this is meant to do:
60 const PUBLIC_COLLECTION = 'as:Public';
61 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
62 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
63 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
65 const TARGET_UNKNOWN = 0;
70 const TARGET_FOLLOWER = 5;
71 const TARGET_ANSWER = 6;
72 const TARGET_GLOBAL = 7;
74 const COMPLETION_NONE = 0;
75 const COMPLETION_ANNOUCE = 1;
76 const COMPLETION_RELAY = 2;
77 const COMPLETION_MANUAL = 3;
78 const COMPLETION_AUTO = 4;
81 * Checks incoming message from the inbox
83 * @param string $body Body string
84 * @param array $header Header lines
85 * @param integer $uid User ID
89 public static function processInbox(string $body, array $header, int $uid)
91 $activity = json_decode($body, true);
92 if (empty($activity)) {
93 Logger::warning('Invalid body.');
97 $ldactivity = JsonLD::compact($activity);
99 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
101 $apcontact = APContact::getByURL($actor);
103 if (empty($apcontact)) {
104 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
106 } elseif (APContact::isRelay($apcontact)) {
107 self::processRelayPost($ldactivity, $actor);
110 APContact::unmarkForArchival($apcontact);
113 $http_signer = HTTPSignature::getSigner($body, $header);
114 if ($http_signer === false) {
115 Logger::warning('Invalid HTTP signature, message will be discarded.');
117 } elseif (empty($http_signer)) {
118 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
121 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
124 $signer = [$http_signer];
126 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
128 if (LDSignature::isSigned($activity)) {
129 $ld_signer = LDSignature::getSigner($activity);
130 if (empty($ld_signer)) {
131 Logger::info('Invalid JSON-LD signature from ' . $actor);
132 } elseif ($ld_signer != $http_signer) {
133 $signer[] = $ld_signer;
135 if (!empty($ld_signer && ($actor == $http_signer))) {
136 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
137 $trust_source = true;
138 } elseif (!empty($ld_signer)) {
139 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
140 $trust_source = true;
141 } elseif ($actor == $http_signer) {
142 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
143 $trust_source = true;
145 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
146 $trust_source = false;
148 } elseif ($actor == $http_signer) {
149 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
150 $trust_source = true;
152 Logger::info('No JSON-LD signature, different actor.');
153 $trust_source = false;
156 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
160 * Process incoming posts from relays
162 * @param array $activity
163 * @param string $actor
166 private static function processRelayPost(array $activity, string $actor)
168 $type = JsonLD::fetchElement($activity, '@type');
170 Logger::info('Empty type', ['activity' => $activity, 'actor' => $actor]);
174 if ($type != 'as:Announce') {
175 Logger::info('Not an announcement', ['activity' => $activity, 'actor' => $actor]);
179 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
180 if (empty($object_id)) {
181 Logger::info('No object id found', ['activity' => $activity, 'actor' => $actor]);
185 $contact = Contact::getByURL($actor);
186 if (empty($contact)) {
187 Logger::info('Relay contact not found', ['actor' => $actor]);
191 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
192 Logger::notice('Relay is no sharer', ['actor' => $actor]);
196 Logger::info('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
198 $item_id = Item::searchByLink($object_id);
200 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
204 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
206 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
210 $item_id = Item::searchByLink($object_id);
212 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
214 Logger::notice('Relayed message had not been stored', ['id' => $object_id, 'actor' => $actor]);
219 * Fetches the object type for a given object id
221 * @param array $activity
222 * @param string $object_id Object ID of the the provided object
223 * @param integer $uid User ID
225 * @return string with object type or NULL
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @throws \ImagickException
229 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
231 if (!empty($activity['as:object'])) {
232 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
233 if (!empty($object_type)) {
238 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
239 // We just assume "note" since it doesn't make a difference for the further processing
243 $profile = APContact::getByURL($object_id);
244 if (!empty($profile['type'])) {
245 APContact::unmarkForArchival($profile);
246 return 'as:' . $profile['type'];
249 $data = ActivityPub::fetchContent($object_id, $uid);
251 $object = JsonLD::compact($data);
252 $type = JsonLD::fetchElement($object, '@type');
262 * Prepare the object array
264 * @param array $activity Array with activity data
265 * @param integer $uid User ID
266 * @param boolean $push Message had been pushed to our system
267 * @param boolean $trust_source Do we trust the source?
269 * @return array with object data
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 * @throws \ImagickException
273 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
275 $id = JsonLD::fetchElement($activity, '@id');
276 if (!empty($id) && !$trust_source) {
277 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
279 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
280 if (!empty($fetched_activity)) {
281 $object = JsonLD::compact($fetched_activity);
282 $fetched_id = JsonLD::fetchElement($object, '@id');
283 if ($fetched_id == $id) {
284 Logger::info('Activity had been fetched successfully', ['id' => $id]);
285 $trust_source = true;
288 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
291 Logger::info('Activity could not been fetched', ['id' => $id]);
295 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
297 Logger::info('Empty actor', ['activity' => $activity]);
301 $type = JsonLD::fetchElement($activity, '@type');
303 // Fetch all receivers from to, cc, bto and bcc
304 $receiverdata = self::getReceivers($activity, $actor);
305 $receivers = $reception_types = [];
306 foreach ($receiverdata as $key => $data) {
307 $receivers[$key] = $data['uid'];
308 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
311 $urls = self::getReceiverURL($activity);
313 // When it is a delivery to a personal inbox we add that user to the receivers
315 $additional = [$uid => $uid];
316 $receivers = array_replace($receivers, $additional);
317 if (empty($activity['thread-completion']) && (empty($reception_types[$uid]) || in_array($reception_types[$uid], [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL]))) {
318 $reception_types[$uid] = self::TARGET_BCC;
319 $owner = User::getOwnerDataById($uid);
320 if (!empty($owner['url'])) {
321 $urls['as:bcc'][] = $owner['url'];
326 // We possibly need some user to fetch private content,
327 // so we fetch one out of the receivers if no uid is provided.
328 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
330 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
331 if (empty($object_id)) {
332 Logger::info('No object found');
336 if (!is_string($object_id)) {
337 Logger::info('Invalid object id', ['object' => $object_id]);
341 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
343 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
344 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
345 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
347 $type = $object_type;
348 $activity = JsonLD::compact($data);
350 // Some variables need to be refetched since the activity changed
351 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
352 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
353 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
357 // Any activities on account types must not be altered
358 if (in_array($object_type, self::ACCOUNT_TYPES)) {
360 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
361 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
362 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
363 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
364 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
365 $object_data['push'] = $push;
366 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
367 // Fetch the content only on activities where this matters
368 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
369 // Always fetch on "Announce"
370 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
371 if (empty($object_data)) {
372 Logger::info("Object data couldn't be processed");
376 $object_data['object_id'] = $object_id;
378 if ($type == 'as:Announce') {
379 $object_data['push'] = false;
381 $object_data['push'] = $push;
384 // Test if it is an answer to a mail
385 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
386 $object_data['directmessage'] = true;
388 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
390 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
391 // Create a mostly empty array out of the activity data (instead of the object).
392 // This way we later don't have to check for the existence of each individual array element.
393 $object_data = self::processObject($activity);
394 $object_data['name'] = $type;
395 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
396 $object_data['object_id'] = $object_id;
397 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
398 $object_data['push'] = $push;
399 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
401 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
402 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
403 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
404 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
405 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
406 $object_data['push'] = $push;
409 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
410 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
411 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
412 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
413 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
414 $object_data['push'] = $push;
416 // An Undo is done on the object of an object, so we need that type as well
417 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
418 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
422 $object_data = self::addActivityFields($object_data, $activity);
424 if (empty($object_data['object_type'])) {
425 $object_data['object_type'] = $object_type;
428 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
429 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
430 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
434 $object_data['type'] = $type;
435 $object_data['actor'] = $actor;
436 $object_data['item_receiver'] = $receivers;
437 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
438 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
440 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
441 // $author = $object_data['author'] ?? $actor;
442 // if (!empty($author) && !empty($object_data['id'])) {
443 // $author_host = parse_url($author, PHP_URL_HOST);
444 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
445 // if ($author_host == $id_host) {
446 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
448 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
449 // $trust_source = false;
453 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
459 * Fetches the first user id from the receiver array
461 * @param array $receivers Array with receivers
462 * @return integer user id;
464 public static function getFirstUserFromReceivers(array $receivers): int
466 foreach ($receivers as $receiver) {
467 if (!empty($receiver)) {
475 * Processes the activity object
477 * @param array $activity Array with activity data
478 * @param string $body The unprocessed body
479 * @param int|null $uid User ID
480 * @param boolean $trust_source Do we trust the source?
481 * @param boolean $push Message had been pushed to our system
482 * @param array $signer The signer of the post
483 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
484 * @throws \ImagickException
486 public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '')
488 $type = JsonLD::fetchElement($activity, '@type');
490 Logger::info('Empty type', ['activity' => $activity]);
494 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
495 Logger::info('Empty object', ['activity' => $activity]);
499 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
501 Logger::info('Empty actor', ['activity' => $activity]);
505 if (is_array($activity['as:object'])) {
506 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
511 // Test the provided signatures against the actor and "attributedTo"
513 if (!empty($attributed_to) && !empty($actor)) {
514 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
516 $trust_source = in_array($actor, $signer);
520 // $trust_source is called by reference and is set to true if the content was retrieved successfully
521 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
522 if (empty($object_data)) {
523 Logger::info('No object data found', ['activity' => $activity]);
527 // Lemmy is announcing activities.
528 // We are changing the announces into regular activities.
529 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
530 $type = $object_data['type'];
533 if (!$trust_source) {
534 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
538 if (!empty($body) && empty($object_data['raw'])) {
539 $object_data['raw'] = $body;
542 // Internal flag for thread completion. See Processor.php
543 if (!empty($activity['thread-completion'])) {
544 $object_data['thread-completion'] = $activity['thread-completion'];
547 if (!empty($activity['completion-mode'])) {
548 $object_data['completion-mode'] = $activity['completion-mode'];
551 if (!empty($activity['thread-children-type'])) {
552 $object_data['thread-children-type'] = $activity['thread-children-type'];
555 // Internal flag for posts that arrived via relay
556 if (!empty($activity['from-relay'])) {
557 $object_data['from-relay'] = $activity['from-relay'];
560 if ($type == 'as:Announce') {
561 $object_data['object_activity'] = $activity;
564 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push);
566 if (!empty($activity['recursion-depth'])) {
567 $object_data['recursion-depth'] = $activity['recursion-depth'];
570 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
571 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
574 if (!self::routeActivities($object_data, $type, $push)) {
575 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
576 Queue::remove($object_data);
583 * @param array $object_data
584 * @param string $type
585 * @param boolean $push
587 * @return boolean Could the activity be routed?
589 public static function routeActivities(array $object_data, string $type, bool $push): bool
591 $activity = $object_data['object_activity'] ?? [];
595 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
596 $item = ActivityPub\Processor::createItem($object_data);
597 ActivityPub\Processor::postItem($object_data, $item);
598 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
599 // Unhandled Peertube activity
600 Queue::remove($object_data);
607 if (in_array($object_data['object_type'], ['as:Event'])) {
608 $item = ActivityPub\Processor::createItem($object_data);
609 ActivityPub\Processor::postItem($object_data, $item);
616 if ($object_data['object_type'] == 'as:tag') {
617 ActivityPub\Processor::addTag($object_data);
618 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
619 ActivityPub\Processor::addToFeaturedCollection($object_data);
620 } elseif ($object_data['object_type'] == '') {
621 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
622 Queue::remove($object_data);
629 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
630 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
631 $object_data['thread-completion'] = Contact::getIdForURL($actor);
632 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
634 $item = ActivityPub\Processor::createItem($object_data);
639 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
640 ActivityPub\Processor::postItem($object_data, $item);
642 if (!empty($activity)) {
643 $announce_object_data = self::processObject($activity);
644 $announce_object_data['name'] = $type;
645 $announce_object_data['author'] = $actor;
646 $announce_object_data['object_id'] = $object_data['object_id'];
647 $announce_object_data['object_type'] = $object_data['object_type'];
648 $announce_object_data['push'] = $push;
650 if (!empty($object_data['raw'])) {
651 $announce_object_data['raw'] = $object_data['raw'];
653 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
661 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
662 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
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 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
674 } elseif ($object_data['object_type'] == '') {
675 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
676 Queue::remove($object_data);
682 case 'as:TentativeAccept':
683 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
684 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
691 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
692 ActivityPub\Processor::updateItem($object_data);
693 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
694 ActivityPub\Processor::updatePerson($object_data);
695 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
696 // Unhandled Peertube activity
697 Queue::remove($object_data);
704 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
705 ActivityPub\Processor::deleteItem($object_data);
706 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
707 ActivityPub\Processor::deletePerson($object_data);
708 } elseif ($object_data['object_type'] == '') {
709 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
710 Queue::remove($object_data);
717 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
718 ActivityPub\Processor::blockAccount($object_data);
725 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
726 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
727 } elseif ($object_data['object_type'] == '') {
728 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
729 Queue::remove($object_data);
736 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
737 ActivityPub\Processor::followUser($object_data);
738 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
739 $object_data['reply-to-id'] = $object_data['object_id'];
740 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
747 if ($object_data['object_type'] == 'as:Follow') {
748 ActivityPub\Processor::acceptFollowUser($object_data);
749 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
750 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
757 if ($object_data['object_type'] == 'as:Follow') {
758 ActivityPub\Processor::rejectFollowUser($object_data);
759 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
760 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
767 if (($object_data['object_type'] == 'as:Follow') &&
768 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
769 ActivityPub\Processor::undoFollowUser($object_data);
770 } elseif (($object_data['object_type'] == 'as:Follow') &&
771 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
772 ActivityPub\Processor::undoActivity($object_data);
773 } elseif (($object_data['object_type'] == 'as:Accept') &&
774 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
775 ActivityPub\Processor::rejectFollowUser($object_data);
776 } elseif (($object_data['object_type'] == 'as:Block') &&
777 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
778 ActivityPub\Processor::unblockAccount($object_data);
779 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
780 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
781 ActivityPub\Processor::undoActivity($object_data);
782 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
783 empty($object_data['object_object_type'])) {
784 // We cannot detect the target object. So we can ignore it.
785 Queue::remove($object_data);
786 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
787 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
788 // Unhandled Peertube activity
789 Queue::remove($object_data);
796 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
797 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
798 } elseif ($object_data['object_type'] == '') {
799 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
800 Queue::remove($object_data);
806 case 'litepub:EmojiReact':
807 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
808 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
809 } elseif ($object_data['object_type'] == '') {
810 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
811 Queue::remove($object_data);
818 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
825 * Stores unhandled or unknown Activities as a file
827 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
828 * @param string $type Activity type
829 * @param array $object_data Preprocessed array that is generated out of the received activity
830 * @param array $activity Array with activity data
831 * @param string $body The unprocessed body
832 * @param integer $uid User ID
833 * @param boolean $trust_source Do we trust the source?
834 * @param boolean $push Message had been pushed to our system
835 * @param array $signer The signer of the post
838 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 = [])
840 if (!DI::config()->get('debug', 'ap_log_unknown')) {
844 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
846 if (!empty($object_data['object_type'])) {
847 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
850 if (!empty($object_data['object_object_type'])) {
851 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
854 $tempfile = tempnam(System::getTempPath(), $file);
855 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));
856 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
860 * Fetch a user id from an activity array
862 * @param array $activity
863 * @param string $actor
865 * @return int user id
867 public static function getBestUserForActivity(array $activity): int
870 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
872 $receivers = self::getReceivers($activity, $actor);
873 foreach ($receivers as $receiver) {
874 if ($receiver['type'] == self::TARGET_GLOBAL) {
877 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
878 $uid = $receiver['uid'];
882 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
884 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
885 if (!empty($contact['uid'])) {
886 $uid = $contact['uid'];
893 // @TODO Missing documentation
894 public static function getReceiverURL(array $activity): array
898 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
899 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
900 if (empty($receiver_list)) {
904 foreach ($receiver_list as $receiver) {
905 if ($receiver == self::PUBLIC_COLLECTION) {
906 $receiver = ActivityPub::PUBLIC_COLLECTION;
908 $urls[$element][] = $receiver;
916 * Fetch the receiver list from an activity array
918 * @param array $activity
919 * @param string $actor
921 * @param boolean $fetch_unlisted
923 * @return array with receivers (user id)
926 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
928 $reply = $receivers = $profile = [];
930 // When it is an answer, we inherite the receivers from the parent
931 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
932 if (!empty($replyto)) {
935 // Fix possibly wrong item URI (could be an answer to a plink uri)
936 $fixedReplyTo = Item::getURIByLink($replyto);
937 if (!empty($fixedReplyTo)) {
938 $reply[] = $fixedReplyTo;
942 // Fetch all posts that refer to the object id
943 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
944 if (!empty($object_id)) {
945 $reply[] = $object_id;
948 if (!empty($reply)) {
949 $parents = Post::select(['uid'], ['uri' => $reply]);
950 while ($parent = Post::fetch($parents)) {
951 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
953 DBA::close($parents);
956 if (!empty($actor)) {
957 $profile = APContact::getByURL($actor);
958 $followers = $profile['followers'] ?? '';
959 $is_forum = ($actor['type'] ?? '') == 'Group';
960 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
962 Logger::info('Empty actor', ['activity' => $activity]);
967 // We have to prevent false follower assumptions upon thread completions
968 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
970 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
971 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
972 if (empty($receiver_list)) {
976 foreach ($receiver_list as $receiver) {
977 if ($receiver == self::PUBLIC_COLLECTION) {
978 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
981 // Add receiver "-1" for unlisted posts
982 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
983 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
986 // Fetch the receivers for the public and the followers collection
987 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
988 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
992 // Fetching all directly addressed receivers
993 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
994 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
995 if (!DBA::isResult($contact)) {
999 // Check if the potential receiver is following the actor
1000 // Exception: The receiver is targetted via "to" or this is a comment
1001 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1002 $networks = Protocol::FEDERATED;
1003 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1004 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1006 // Forum posts are only accepted from forum contacts
1007 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1008 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1011 if (!DBA::exists('contact', $condition)) {
1016 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1017 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1020 $type = self::TARGET_TO;
1023 $type = self::TARGET_CC;
1026 $type = self::TARGET_BTO;
1029 $type = self::TARGET_BCC;
1033 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1038 self::switchContacts($receivers, $actor);
1044 * Fetch the receiver list of a given actor
1046 * @param string $actor
1047 * @param array $tags
1048 * @param array $receivers
1049 * @param integer $target_type
1050 * @param array $profile
1052 * @return array with receivers (user id)
1053 * @throws \Exception
1055 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1057 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1058 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1060 if (!empty($profile['uri-id'])) {
1061 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1062 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1063 while ($contact = DBA::fetch($contacts)) {
1064 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1065 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1068 DBA::close($contacts);
1070 // This part will only be called while post update 1426 wasn't finished
1071 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1072 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1073 while ($contact = DBA::fetch($contacts)) {
1074 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1075 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1078 DBA::close($contacts);
1080 // The queries are split because of performance issues
1081 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1082 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1083 while ($contact = DBA::fetch($contacts)) {
1084 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1085 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1088 DBA::close($contacts);
1094 * Tests if the contact is a valid receiver for this actor
1096 * @param array $contact
1097 * @param array $tags
1099 * @return bool with receivers (user id)
1100 * @throws \Exception
1102 private static function isValidReceiverForActor(array $contact, array $tags): bool
1104 // Are we following the contact? Then this is a valid receiver
1105 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1109 // When the possible receiver isn't a community, then it is no valid receiver
1110 $owner = User::getOwnerDataById($contact['uid']);
1111 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1115 // Is the community account tagged?
1116 foreach ($tags as $tag) {
1117 if ($tag['type'] != 'Mention') {
1121 if (Strings::compareLink($tag['href'], $owner['url'])) {
1130 * Switches existing contacts to ActivityPub
1132 * @param integer $cid Contact ID
1133 * @param integer $uid User ID
1134 * @param string $url Profile URL
1136 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1137 * @throws \ImagickException
1139 public static function switchContact(int $cid, int $uid, string $url)
1141 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1142 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1146 if (Contact::updateFromProbe($cid)) {
1147 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1150 // Send a new follow request to be sure that the connection still exists
1151 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1152 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1153 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1158 * @TODO Fix documentation and type-hints
1163 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1164 * @throws \ImagickException
1166 private static function switchContacts($receivers, $actor)
1168 if (empty($actor)) {
1172 foreach ($receivers as $receiver) {
1173 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1174 if (DBA::isResult($contact)) {
1175 self::switchContact($contact['id'], $receiver['uid'], $actor);
1178 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1179 if (DBA::isResult($contact)) {
1180 self::switchContact($contact['id'], $receiver['uid'], $actor);
1186 * @TODO Fix documentation and type-hints
1188 * @param $object_data
1189 * @param array $activity
1193 private static function addActivityFields($object_data, array $activity)
1195 if (!empty($activity['published']) && empty($object_data['published'])) {
1196 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1199 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1200 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1203 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1204 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1206 if (!empty($object_data['object_id'])) {
1207 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1208 $objectId = Item::getURIByLink($object_data['object_id']);
1209 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1210 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1211 $object_data['object_id'] = $objectId;
1215 return $object_data;
1219 * Fetches the object data from external ressources if needed
1221 * @param string $object_id Object ID of the the provided object
1222 * @param array $object The provided object array
1223 * @param boolean $trust_source Do we trust the provided object?
1224 * @param integer $uid User ID for the signature that we use to fetch data
1226 * @return array|false with trusted and valid object data
1227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228 * @throws \ImagickException
1230 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1232 // By fetching the type we check if the object is complete.
1233 $type = JsonLD::fetchElement($object, '@type');
1235 if (!$trust_source || empty($type)) {
1236 $data = ActivityPub::fetchContent($object_id, $uid);
1237 if (!empty($data)) {
1238 $object = JsonLD::compact($data);
1239 Logger::info('Fetched content for ' . $object_id);
1241 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1243 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1244 if (!DBA::isResult($item)) {
1245 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1248 Logger::info('Using already stored item for url ' . $object_id);
1249 $data = ActivityPub\Transmitter::createNote($item);
1250 $object = JsonLD::compact($data);
1253 $id = JsonLD::fetchElement($object, '@id');
1255 Logger::info('Empty id');
1259 if ($id != $object_id) {
1260 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1264 Logger::info('Using original object for url ' . $object_id);
1267 $type = JsonLD::fetchElement($object, '@type');
1269 Logger::info('Empty type');
1273 // Lemmy is resharing "create" activities instead of content
1274 // We fetch the content from the activity.
1275 if (in_array($type, ['as:Create'])) {
1276 $object = $object['as:object'];
1277 $type = JsonLD::fetchElement($object, '@type');
1279 Logger::info('Empty type');
1282 $object_data = self::processObject($object);
1285 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1286 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1287 $object_data = self::processObject($object);
1289 if (!empty($data)) {
1290 $object_data['raw'] = json_encode($data);
1292 return $object_data;
1295 if ($type == 'as:Announce') {
1296 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1297 if (empty($object_id) || !is_string($object_id)) {
1300 return self::fetchObject($object_id, [], false, $uid);
1303 Logger::info('Unhandled object type: ' . $type);
1308 * Converts the language element (Used by Peertube)
1310 * @param array $languages
1311 * @return array Languages
1313 public static function processLanguages(array $languages): array
1315 if (empty($languages)) {
1319 $language_list = [];
1321 foreach ($languages as $language) {
1322 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1323 $language_list[$language['_:identifier']] = $language['as:name'];
1326 return $language_list;
1330 * Convert tags from JSON-LD format into a simplified format
1332 * @param array $tags Tags in JSON-LD format
1334 * @return array with tags in a simplified format
1336 public static function processTags(array $tags): array
1340 foreach ($tags as $tag) {
1345 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1346 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1347 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1349 if (empty($element['type'])) {
1353 if (empty($element['href'])) {
1354 $element['href'] = $element['name'];
1357 $taglist[] = $element;
1363 * Convert emojis from JSON-LD format into a simplified format
1365 * @param array $emojis
1366 * @return array with emojis in a simplified format
1368 private static function processEmojis(array $emojis): array
1372 foreach ($emojis as $emoji) {
1373 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1377 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1378 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1381 $emojilist[] = $element;
1388 * Convert attachments from JSON-LD format into a simplified format
1390 * @param array $attachments Attachments in JSON-LD format
1392 * @return array Attachments in a simplified format
1394 private static function processAttachments(array $attachments): array
1398 // Removes empty values
1399 $attachments = array_filter($attachments);
1401 foreach ($attachments as $attachment) {
1402 switch (JsonLD::fetchElement($attachment, '@type')) {
1407 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1408 foreach ($urls as $url) {
1409 // Single scalar URL case
1410 if (is_string($url)) {
1415 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1416 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1417 if (Strings::startsWith($mediaType, 'image')) {
1426 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1427 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1429 'image' => $pageImage,
1433 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1434 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1435 $imagePreviewUrl = null;
1437 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1438 $imageVariants = [];
1439 $previewVariants = [];
1440 foreach ($urls as $url) {
1441 // Scalar URL, no discrimination possible
1442 if (is_string($url)) {
1443 $imageFullUrl = $url;
1447 // Not sure what to do with a different Link media type than the base Image, we skip
1448 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1452 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1454 // Default URL choice if no discriminating width is provided
1455 $imageFullUrl = $href ?? $imageFullUrl;
1457 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1459 if ($href && $width) {
1460 $imageVariants[$width] = $href;
1461 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1462 $previewVariants[abs(632 - $width)] = $href;
1466 if ($imageVariants) {
1467 // Taking the maximum size image
1468 ksort($imageVariants);
1469 $imageFullUrl = array_pop($imageVariants);
1471 // Taking the minimum number distance to the target distance
1472 ksort($previewVariants);
1473 $imagePreviewUrl = array_shift($previewVariants);
1476 unset($imageVariants);
1477 unset($previewVariants);
1481 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1482 'mediaType' => $mediaType,
1483 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1484 'url' => $imageFullUrl,
1485 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1490 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1491 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1492 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1493 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1494 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1495 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1496 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1505 * Convert questions from JSON-LD format into a simplified format
1507 * @param array $object
1509 * @return array Questions in a simplified format
1511 private static function processQuestion(array $object): array
1515 if (!empty($object['as:oneOf'])) {
1516 $question['multiple'] = false;
1517 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1518 } elseif (!empty($object['as:anyOf'])) {
1519 $question['multiple'] = true;
1520 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1525 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1526 if (!empty($closed)) {
1527 $question['end-time'] = $closed;
1529 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1532 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1533 $question['options'] = [];
1537 foreach ($options as $option) {
1538 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1542 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1544 if (empty($option['as:replies'])) {
1548 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1550 $question['options'][] = ['name' => $name, 'replies' => $replies];
1552 $voters += (int)$replies;
1555 // For single choice question we can count the number of voters if not provided (like with Misskey)
1556 if (empty($question['voters']) && !$question['multiple']) {
1557 $question['voters'] = $voters;
1564 * Fetch the original source or content with the "language" Markdown or HTML
1566 * @param array $object
1567 * @param array $object_data
1569 * @return array Object data (?)
1570 * @throws \Exception
1572 private static function getSource(array $object, array $object_data): array
1574 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1575 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1576 if (!empty($object_data['source'])) {
1577 return $object_data;
1580 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1581 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1582 if (!empty($object_data['source'])) {
1583 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1584 return $object_data;
1587 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1588 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1589 if (!empty($object_data['source'])) {
1590 $object_data['source'] = HTML::toBBCode($object_data['source']);
1591 return $object_data;
1594 return $object_data;
1598 * Extracts a potential alternate URL from a list of additional URL elements
1600 * @param array $urls
1603 private static function extractAlternateUrl(array $urls): string
1606 foreach ($urls as $key => $url) {
1607 // Not a list but a single URL element
1608 if (!is_numeric($key)) {
1612 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1616 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1621 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1622 if (empty($mediatype)) {
1626 if ($mediatype == 'text/html') {
1627 $alternateUrl = $href;
1631 return $alternateUrl;
1635 * Check if the "as:url" element is an array with multiple links
1636 * This is the case with audio and video posts.
1637 * Then the links are added as attachments
1639 * @param array $urls The object URL list
1640 * @return array an array of attachments
1642 private static function processAttachmentUrls(array $urls): array
1645 foreach ($urls as $key => $url) {
1646 // Not a list but a single URL element
1647 if (!is_numeric($key)) {
1651 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1655 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1660 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1661 if (empty($mediatype)) {
1665 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1667 if ($filetype == 'audio') {
1668 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1669 } elseif ($filetype == 'video') {
1670 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1671 // PeerTube audio-only track
1672 if ($height === 0) {
1676 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1677 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1678 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1679 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1681 // For Torrent links we always store the highest resolution
1682 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1686 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1687 } elseif ($mediatype == 'application/x-mpegURL') {
1688 // PeerTube exception, actual video link is in the tags of this URL element
1689 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1693 return array_values($attachments);
1697 * Fetches data from the object part of an activity
1699 * @param array $object
1701 * @return array|bool Object data or FALSE if $object does not contain @id element
1702 * @throws \Exception
1704 private static function processObject(array $object)
1706 if (!JsonLD::fetchElement($object, '@id')) {
1711 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1712 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1713 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1715 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1716 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1717 $object_data['reply-to-id'] = $object_data['id'];
1719 // On activities the "reply to" is the id of the object it refers to
1720 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1721 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1722 if (!empty($object_id)) {
1723 $object_data['reply-to-id'] = $object_id;
1727 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1728 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1729 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1730 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1731 $object_data['reply-to-id'] = $replyToId;
1735 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1736 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1738 if (empty($object_data['updated'])) {
1739 $object_data['updated'] = $object_data['published'];
1742 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1743 $object_data['published'] = $object_data['updated'];
1746 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1747 if (empty($actor)) {
1748 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1751 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1752 $location = JsonLD::fetchElement($location, 'location', '@value');
1754 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1755 // down to HTML and then finally format to plaintext.
1756 $location = Markdown::convert($location);
1757 $location = BBCode::toPlaintext($location);
1760 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1761 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1762 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1763 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1764 $object_data['actor'] = $object_data['author'] = $actor;
1765 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1766 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1767 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1768 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1769 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1770 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1771 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1772 $object_data = self::getSource($object, $object_data);
1773 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1774 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1775 $object_data['location'] = $location;
1776 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1777 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1778 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1779 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1780 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1781 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1782 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1783 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1784 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1785 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1786 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1788 // Special treatment for Hubzilla links
1789 if (is_array($object_data['alternate-url'])) {
1790 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1792 if (!is_string($object_data['alternate-url'])) {
1793 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1797 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1798 $object_data['alternate-url'] = null;
1801 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1802 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1803 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1806 // For page types we expect that the alternate url posts to some page.
1807 // So we add this to the attachments if it differs from the id.
1808 // Currently only Lemmy is using the page type.
1809 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1810 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1811 $object_data['alternate-url'] = null;
1814 if ($object_data['object_type'] == 'as:Question') {
1815 $object_data['question'] = self::processQuestion($object);
1818 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1819 $receivers = $reception_types = [];
1820 foreach ($receiverdata as $key => $data) {
1821 $receivers[$key] = $data['uid'];
1822 $reception_types[$data['uid']] = $data['type'] ?? 0;
1825 $object_data['receiver_urls'] = self::getReceiverURL($object);
1826 $object_data['receiver'] = $receivers;
1827 $object_data['reception_type'] = $reception_types;
1829 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1830 unset($object_data['receiver'][-1]);
1831 unset($object_data['reception_type'][-1]);
1833 // Common object data:
1836 // @context, type, actor, signature, mediaType, duration, replies, icon
1838 // Also missing: (Defined in the standard, but currently unused)
1839 // audience, preview, endTime, startTime, image
1844 // contentMap, announcement_count, announcements, context_id, likes, like_count
1845 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1850 // category, licence, language, commentsEnabled
1853 // views, waitTranscoding, state, support, subtitleLanguage
1854 // likes, dislikes, shares, comments
1856 return $object_data;