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 $type = JsonLD::fetchElement($activity, '@type');
277 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
279 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
280 $fetch_id = $object_id;
285 if (!empty($activity['as:object'])) {
286 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
289 if (!empty($id) && !$trust_source) {
290 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
292 $fetched_activity = ActivityPub::fetchContent($fetch_id, $fetch_uid);
293 if (!empty($fetched_activity)) {
294 $object = JsonLD::compact($fetched_activity);
296 $fetched_id = JsonLD::fetchElement($object, '@id');
297 $fetched_type = JsonLD::fetchElement($object, '@type');
299 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
300 Logger::info('Activity had been fetched successfully', ['id' => $id]);
301 $trust_source = true;
303 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
304 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
305 $trust_source = true;
306 unset($object['@context']);
307 $activity['as:object'] = $object;
309 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
312 Logger::info('Activity could not been fetched', ['id' => $id]);
316 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
318 Logger::info('Empty actor', ['activity' => $activity]);
322 $type = JsonLD::fetchElement($activity, '@type');
324 // Fetch all receivers from to, cc, bto and bcc
325 $receiverdata = self::getReceivers($activity, $actor);
326 $receivers = $reception_types = [];
327 foreach ($receiverdata as $key => $data) {
328 $receivers[$key] = $data['uid'];
329 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
332 $urls = self::getReceiverURL($activity);
334 // When it is a delivery to a personal inbox we add that user to the receivers
336 $additional = [$uid => $uid];
337 $receivers = array_replace($receivers, $additional);
338 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]))) {
339 $reception_types[$uid] = self::TARGET_BCC;
340 $owner = User::getOwnerDataById($uid);
341 if (!empty($owner['url'])) {
342 $urls['as:bcc'][] = $owner['url'];
347 // We possibly need some user to fetch private content,
348 // so we fetch one out of the receivers if no uid is provided.
349 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
351 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
352 if (empty($object_id)) {
353 Logger::info('No object found');
357 if (!is_string($object_id)) {
358 Logger::info('Invalid object id', ['object' => $object_id]);
362 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
364 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
365 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
366 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
368 $type = $object_type;
369 $activity = JsonLD::compact($data);
371 // Some variables need to be refetched since the activity changed
372 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
373 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
374 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
378 // Any activities on account types must not be altered
379 if (in_array($object_type, self::ACCOUNT_TYPES)) {
381 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
382 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
383 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
384 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
385 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
386 $object_data['push'] = $push;
387 if (!$trust_source && ($type == 'as:Delete')) {
388 $apcontact = APContact::getByURL($object_data['object_id'], true);
389 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
391 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
392 // Fetch the content only on activities where this matters
393 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
394 // Always fetch on "Announce"
395 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
396 if (empty($object_data)) {
397 Logger::info("Object data couldn't be processed");
401 $object_data['object_id'] = $object_id;
403 if ($type == 'as:Announce') {
404 $object_data['push'] = false;
406 $object_data['push'] = $push;
409 // Test if it is an answer to a mail
410 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
411 $object_data['directmessage'] = true;
413 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
415 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
416 // Create a mostly empty array out of the activity data (instead of the object).
417 // This way we later don't have to check for the existence of each individual array element.
418 $object_data = self::processObject($activity);
419 $object_data['name'] = $type;
420 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
421 $object_data['object_id'] = $object_id;
422 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
423 $object_data['push'] = $push;
424 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
426 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
427 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
428 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
429 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
430 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
431 $object_data['push'] = $push;
434 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
435 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
436 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
437 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
438 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
439 $object_data['push'] = $push;
441 // An Undo is done on the object of an object, so we need that type as well
442 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
443 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
446 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
447 $trust_source = Processor::isActivityGone($object_data['object_id']);
448 if (!$trust_source) {
449 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
454 $object_data = self::addActivityFields($object_data, $activity);
456 if (empty($object_data['object_type'])) {
457 $object_data['object_type'] = $object_type;
460 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
461 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
462 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
466 $object_data['type'] = $type;
467 $object_data['actor'] = $actor;
468 $object_data['item_receiver'] = $receivers;
469 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
470 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
472 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
473 // $author = $object_data['author'] ?? $actor;
474 // if (!empty($author) && !empty($object_data['id'])) {
475 // $author_host = parse_url($author, PHP_URL_HOST);
476 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
477 // if ($author_host == $id_host) {
478 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
480 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
481 // $trust_source = false;
485 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
491 * Fetches the first user id from the receiver array
493 * @param array $receivers Array with receivers
494 * @return integer user id;
496 public static function getFirstUserFromReceivers(array $receivers): int
498 foreach ($receivers as $receiver) {
499 if (!empty($receiver)) {
507 * Processes the activity object
509 * @param array $activity Array with activity data
510 * @param string $body The unprocessed body
511 * @param int|null $uid User ID
512 * @param boolean $trust_source Do we trust the source?
513 * @param boolean $push Message had been pushed to our system
514 * @param array $signer The signer of the post
515 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
516 * @throws \ImagickException
518 public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '')
520 $type = JsonLD::fetchElement($activity, '@type');
522 Logger::info('Empty type', ['activity' => $activity]);
526 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
527 Logger::info('Empty object', ['activity' => $activity]);
531 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
533 Logger::info('Empty actor', ['activity' => $activity]);
537 if (is_array($activity['as:object'])) {
538 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
543 // Test the provided signatures against the actor and "attributedTo"
545 if (!empty($attributed_to) && !empty($actor)) {
546 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
548 $trust_source = in_array($actor, $signer);
552 // $trust_source is called by reference and is set to true if the content was retrieved successfully
553 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
554 if (empty($object_data)) {
555 Logger::info('No object data found', ['activity' => $activity]);
559 // Lemmy is announcing activities.
560 // We are changing the announces into regular activities.
561 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
562 $type = $object_data['type'];
565 if (!empty($body) && empty($object_data['raw'])) {
566 $object_data['raw'] = $body;
569 // Internal flag for thread completion. See Processor.php
570 if (!empty($activity['thread-completion'])) {
571 $object_data['thread-completion'] = $activity['thread-completion'];
574 if (!empty($activity['completion-mode'])) {
575 $object_data['completion-mode'] = $activity['completion-mode'];
578 if (!empty($activity['thread-children-type'])) {
579 $object_data['thread-children-type'] = $activity['thread-children-type'];
582 // Internal flag for posts that arrived via relay
583 if (!empty($activity['from-relay'])) {
584 $object_data['from-relay'] = $activity['from-relay'];
587 if ($type == 'as:Announce') {
588 $object_data['object_activity'] = $activity;
591 if ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted')) {
592 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
595 if (!$trust_source) {
596 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
600 if (!empty($activity['recursion-depth'])) {
601 $object_data['recursion-depth'] = $activity['recursion-depth'];
604 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
605 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
608 if (!self::routeActivities($object_data, $type, $push)) {
609 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
610 Queue::remove($object_data);
617 * @param array $object_data
618 * @param string $type
619 * @param boolean $push
621 * @return boolean Could the activity be routed?
623 public static function routeActivities(array $object_data, string $type, bool $push): bool
625 $activity = $object_data['object_activity'] ?? [];
629 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
630 $item = ActivityPub\Processor::createItem($object_data);
631 ActivityPub\Processor::postItem($object_data, $item);
632 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
633 // Unhandled Peertube activity
634 Queue::remove($object_data);
641 if (in_array($object_data['object_type'], ['as:Event'])) {
642 $item = ActivityPub\Processor::createItem($object_data);
643 ActivityPub\Processor::postItem($object_data, $item);
650 if ($object_data['object_type'] == 'as:tag') {
651 ActivityPub\Processor::addTag($object_data);
652 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
653 ActivityPub\Processor::addToFeaturedCollection($object_data);
654 } elseif ($object_data['object_type'] == '') {
655 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
656 Queue::remove($object_data);
663 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
664 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
665 $object_data['thread-completion'] = Contact::getIdForURL($actor);
666 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
668 $item = ActivityPub\Processor::createItem($object_data);
673 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
674 ActivityPub\Processor::postItem($object_data, $item);
676 if (!empty($activity)) {
677 $announce_object_data = self::processObject($activity);
678 $announce_object_data['name'] = $type;
679 $announce_object_data['author'] = $actor;
680 $announce_object_data['object_id'] = $object_data['object_id'];
681 $announce_object_data['object_type'] = $object_data['object_type'];
682 $announce_object_data['push'] = $push;
684 if (!empty($object_data['raw'])) {
685 $announce_object_data['raw'] = $object_data['raw'];
687 if (!empty($object_data['raw-object'])) {
688 $announce_object_data['raw-object'] = $object_data['raw-object'];
690 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
698 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
699 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
700 } elseif ($object_data['object_type'] == '') {
701 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
702 Queue::remove($object_data);
709 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
710 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
711 } elseif ($object_data['object_type'] == '') {
712 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
713 Queue::remove($object_data);
719 case 'as:TentativeAccept':
720 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
721 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
728 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
729 ActivityPub\Processor::updateItem($object_data);
730 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
731 ActivityPub\Processor::updatePerson($object_data);
732 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
733 // Unhandled Peertube activity
734 Queue::remove($object_data);
741 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
742 ActivityPub\Processor::deleteItem($object_data);
743 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
744 ActivityPub\Processor::deletePerson($object_data);
745 } elseif ($object_data['object_type'] == '') {
746 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
747 Queue::remove($object_data);
754 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
755 ActivityPub\Processor::blockAccount($object_data);
762 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
763 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
764 } elseif ($object_data['object_type'] == '') {
765 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
766 Queue::remove($object_data);
773 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
774 ActivityPub\Processor::followUser($object_data);
775 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
776 $object_data['reply-to-id'] = $object_data['object_id'];
777 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
784 if ($object_data['object_type'] == 'as:Follow') {
785 ActivityPub\Processor::acceptFollowUser($object_data);
786 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
787 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
794 if ($object_data['object_type'] == 'as:Follow') {
795 ActivityPub\Processor::rejectFollowUser($object_data);
796 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
797 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
804 if (($object_data['object_type'] == 'as:Follow') &&
805 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
806 ActivityPub\Processor::undoFollowUser($object_data);
807 } elseif (($object_data['object_type'] == 'as:Follow') &&
808 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
809 ActivityPub\Processor::undoActivity($object_data);
810 } elseif (($object_data['object_type'] == 'as:Accept') &&
811 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
812 ActivityPub\Processor::rejectFollowUser($object_data);
813 } elseif (($object_data['object_type'] == 'as:Block') &&
814 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
815 ActivityPub\Processor::unblockAccount($object_data);
816 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
817 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
818 ActivityPub\Processor::undoActivity($object_data);
819 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
820 empty($object_data['object_object_type'])) {
821 // We cannot detect the target object. So we can ignore it.
822 Queue::remove($object_data);
823 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
824 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
825 // Unhandled Peertube activity
826 Queue::remove($object_data);
833 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
834 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
835 } elseif ($object_data['object_type'] == '') {
836 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
837 Queue::remove($object_data);
843 case 'litepub:EmojiReact':
844 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
845 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
846 } elseif ($object_data['object_type'] == '') {
847 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
848 Queue::remove($object_data);
855 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
862 * Stores unhandled or unknown Activities as a file
864 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
865 * @param string $type Activity type
866 * @param array $object_data Preprocessed array that is generated out of the received activity
867 * @param array $activity Array with activity data
868 * @param string $body The unprocessed body
869 * @param integer $uid User ID
870 * @param boolean $trust_source Do we trust the source?
871 * @param boolean $push Message had been pushed to our system
872 * @param array $signer The signer of the post
875 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 = [])
877 if (!DI::config()->get('debug', 'ap_log_unknown')) {
881 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
883 if (!empty($object_data['object_type'])) {
884 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
887 if (!empty($object_data['object_object_type'])) {
888 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
891 $tempfile = tempnam(System::getTempPath(), $file);
892 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));
893 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
897 * Fetch a user id from an activity array
899 * @param array $activity
900 * @param string $actor
902 * @return int user id
904 public static function getBestUserForActivity(array $activity): int
907 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
909 $receivers = self::getReceivers($activity, $actor);
910 foreach ($receivers as $receiver) {
911 if ($receiver['type'] == self::TARGET_GLOBAL) {
914 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
915 $uid = $receiver['uid'];
919 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
921 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
922 if (!empty($contact['uid'])) {
923 $uid = $contact['uid'];
930 // @TODO Missing documentation
931 public static function getReceiverURL(array $activity): array
935 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
936 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
937 if (empty($receiver_list)) {
941 foreach ($receiver_list as $receiver) {
942 if ($receiver == self::PUBLIC_COLLECTION) {
943 $receiver = ActivityPub::PUBLIC_COLLECTION;
945 $urls[$element][] = $receiver;
953 * Fetch the receiver list from an activity array
955 * @param array $activity
956 * @param string $actor
958 * @param boolean $fetch_unlisted
960 * @return array with receivers (user id)
963 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
965 $reply = $receivers = $profile = [];
967 // When it is an answer, we inherite the receivers from the parent
968 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
969 if (!empty($replyto)) {
972 // Fix possibly wrong item URI (could be an answer to a plink uri)
973 $fixedReplyTo = Item::getURIByLink($replyto);
974 if (!empty($fixedReplyTo)) {
975 $reply[] = $fixedReplyTo;
979 // Fetch all posts that refer to the object id
980 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
981 if (!empty($object_id)) {
982 $reply[] = $object_id;
985 if (!empty($reply)) {
986 $parents = Post::select(['uid'], ['uri' => $reply]);
987 while ($parent = Post::fetch($parents)) {
988 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
990 DBA::close($parents);
993 if (!empty($actor)) {
994 $profile = APContact::getByURL($actor);
995 $followers = $profile['followers'] ?? '';
996 $is_forum = ($actor['type'] ?? '') == 'Group';
997 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
999 Logger::info('Empty actor', ['activity' => $activity]);
1004 // We have to prevent false follower assumptions upon thread completions
1005 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1007 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1008 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1009 if (empty($receiver_list)) {
1013 foreach ($receiver_list as $receiver) {
1014 if ($receiver == self::PUBLIC_COLLECTION) {
1015 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1018 // Add receiver "-1" for unlisted posts
1019 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1020 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1023 // Fetch the receivers for the public and the followers collection
1024 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1025 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1029 // Fetching all directly addressed receivers
1030 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1031 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1032 if (!DBA::isResult($contact)) {
1036 // Check if the potential receiver is following the actor
1037 // Exception: The receiver is targetted via "to" or this is a comment
1038 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1039 $networks = Protocol::FEDERATED;
1040 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1041 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1043 // Forum posts are only accepted from forum contacts
1044 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1045 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1048 if (!DBA::exists('contact', $condition)) {
1053 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1054 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1057 $type = self::TARGET_TO;
1060 $type = self::TARGET_CC;
1063 $type = self::TARGET_BTO;
1066 $type = self::TARGET_BCC;
1070 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1075 self::switchContacts($receivers, $actor);
1081 * Fetch the receiver list of a given actor
1083 * @param string $actor
1084 * @param array $tags
1085 * @param array $receivers
1086 * @param integer $target_type
1087 * @param array $profile
1089 * @return array with receivers (user id)
1090 * @throws \Exception
1092 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1094 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1095 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1097 if (!empty($profile['uri-id'])) {
1098 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1099 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1100 while ($contact = DBA::fetch($contacts)) {
1101 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1102 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1105 DBA::close($contacts);
1107 // This part will only be called while post update 1426 wasn't finished
1108 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1109 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1110 while ($contact = DBA::fetch($contacts)) {
1111 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1112 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1115 DBA::close($contacts);
1117 // The queries are split because of performance issues
1118 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1119 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1120 while ($contact = DBA::fetch($contacts)) {
1121 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1122 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1125 DBA::close($contacts);
1131 * Tests if the contact is a valid receiver for this actor
1133 * @param array $contact
1134 * @param array $tags
1136 * @return bool with receivers (user id)
1137 * @throws \Exception
1139 private static function isValidReceiverForActor(array $contact, array $tags): bool
1141 // Are we following the contact? Then this is a valid receiver
1142 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1146 // When the possible receiver isn't a community, then it is no valid receiver
1147 $owner = User::getOwnerDataById($contact['uid']);
1148 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1152 // Is the community account tagged?
1153 foreach ($tags as $tag) {
1154 if ($tag['type'] != 'Mention') {
1158 if (Strings::compareLink($tag['href'], $owner['url'])) {
1167 * Switches existing contacts to ActivityPub
1169 * @param integer $cid Contact ID
1170 * @param integer $uid User ID
1171 * @param string $url Profile URL
1173 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1174 * @throws \ImagickException
1176 public static function switchContact(int $cid, int $uid, string $url)
1178 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1179 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1183 if (Contact::updateFromProbe($cid)) {
1184 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1187 // Send a new follow request to be sure that the connection still exists
1188 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1189 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1190 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1195 * @TODO Fix documentation and type-hints
1200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1201 * @throws \ImagickException
1203 private static function switchContacts($receivers, $actor)
1205 if (empty($actor)) {
1209 foreach ($receivers as $receiver) {
1210 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1211 if (DBA::isResult($contact)) {
1212 self::switchContact($contact['id'], $receiver['uid'], $actor);
1215 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1216 if (DBA::isResult($contact)) {
1217 self::switchContact($contact['id'], $receiver['uid'], $actor);
1223 * @TODO Fix documentation and type-hints
1225 * @param $object_data
1226 * @param array $activity
1230 private static function addActivityFields($object_data, array $activity)
1232 if (!empty($activity['published']) && empty($object_data['published'])) {
1233 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1236 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1237 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1240 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1241 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1243 if (!empty($object_data['object_id'])) {
1244 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1245 $objectId = Item::getURIByLink($object_data['object_id']);
1246 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1247 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1248 $object_data['object_id'] = $objectId;
1252 return $object_data;
1256 * Fetches the object data from external ressources if needed
1258 * @param string $object_id Object ID of the the provided object
1259 * @param array $object The provided object array
1260 * @param boolean $trust_source Do we trust the provided object?
1261 * @param integer $uid User ID for the signature that we use to fetch data
1263 * @return array|false with trusted and valid object data
1264 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1265 * @throws \ImagickException
1267 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1269 // By fetching the type we check if the object is complete.
1270 $type = JsonLD::fetchElement($object, '@type');
1272 if (!$trust_source || empty($type)) {
1273 $data = ActivityPub::fetchContent($object_id, $uid);
1274 if (!empty($data)) {
1275 $object = JsonLD::compact($data);
1276 Logger::info('Fetched content for ' . $object_id);
1278 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1280 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1281 if (!DBA::isResult($item)) {
1282 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1285 Logger::info('Using already stored item for url ' . $object_id);
1286 $data = ActivityPub\Transmitter::createNote($item);
1287 $object = JsonLD::compact($data);
1290 $id = JsonLD::fetchElement($object, '@id');
1292 Logger::info('Empty id');
1296 if ($id != $object_id) {
1297 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1301 Logger::info('Using original object for url ' . $object_id);
1304 $type = JsonLD::fetchElement($object, '@type');
1306 Logger::info('Empty type');
1310 // Lemmy is resharing "create" activities instead of content
1311 // We fetch the content from the activity.
1312 if (in_array($type, ['as:Create'])) {
1313 $object = $object['as:object'];
1314 $type = JsonLD::fetchElement($object, '@type');
1316 Logger::info('Empty type');
1319 $object_data = self::processObject($object);
1322 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1323 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1324 $object_data = self::processObject($object);
1326 if (!empty($data)) {
1327 $object_data['raw-object'] = json_encode($data);
1329 return $object_data;
1332 if ($type == 'as:Announce') {
1333 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1334 if (empty($object_id) || !is_string($object_id)) {
1337 return self::fetchObject($object_id, [], false, $uid);
1340 Logger::info('Unhandled object type: ' . $type);
1345 * Converts the language element (Used by Peertube)
1347 * @param array $languages
1348 * @return array Languages
1350 public static function processLanguages(array $languages): array
1352 if (empty($languages)) {
1356 $language_list = [];
1358 foreach ($languages as $language) {
1359 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1360 $language_list[$language['_:identifier']] = $language['as:name'];
1363 return $language_list;
1367 * Convert tags from JSON-LD format into a simplified format
1369 * @param array $tags Tags in JSON-LD format
1371 * @return array with tags in a simplified format
1373 public static function processTags(array $tags): array
1377 foreach ($tags as $tag) {
1382 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1383 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1384 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1386 if (empty($element['type'])) {
1390 if (empty($element['href'])) {
1391 $element['href'] = $element['name'];
1394 $taglist[] = $element;
1400 * Convert emojis from JSON-LD format into a simplified format
1402 * @param array $emojis
1403 * @return array with emojis in a simplified format
1405 private static function processEmojis(array $emojis): array
1409 foreach ($emojis as $emoji) {
1410 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1414 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1415 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1418 $emojilist[] = $element;
1425 * Convert attachments from JSON-LD format into a simplified format
1427 * @param array $attachments Attachments in JSON-LD format
1429 * @return array Attachments in a simplified format
1431 private static function processAttachments(array $attachments): array
1435 // Removes empty values
1436 $attachments = array_filter($attachments);
1438 foreach ($attachments as $attachment) {
1439 switch (JsonLD::fetchElement($attachment, '@type')) {
1444 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1445 foreach ($urls as $url) {
1446 // Single scalar URL case
1447 if (is_string($url)) {
1452 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1453 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1454 if (Strings::startsWith($mediaType, 'image')) {
1463 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1464 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1466 'image' => $pageImage,
1470 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1471 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1472 $imagePreviewUrl = null;
1474 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1475 $imageVariants = [];
1476 $previewVariants = [];
1477 foreach ($urls as $url) {
1478 // Scalar URL, no discrimination possible
1479 if (is_string($url)) {
1480 $imageFullUrl = $url;
1484 // Not sure what to do with a different Link media type than the base Image, we skip
1485 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1489 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1491 // Default URL choice if no discriminating width is provided
1492 $imageFullUrl = $href ?? $imageFullUrl;
1494 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1496 if ($href && $width) {
1497 $imageVariants[$width] = $href;
1498 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1499 $previewVariants[abs(632 - $width)] = $href;
1503 if ($imageVariants) {
1504 // Taking the maximum size image
1505 ksort($imageVariants);
1506 $imageFullUrl = array_pop($imageVariants);
1508 // Taking the minimum number distance to the target distance
1509 ksort($previewVariants);
1510 $imagePreviewUrl = array_shift($previewVariants);
1513 unset($imageVariants);
1514 unset($previewVariants);
1518 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1519 'mediaType' => $mediaType,
1520 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1521 'url' => $imageFullUrl,
1522 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1527 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1528 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1529 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1530 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1531 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1532 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1533 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1542 * Convert questions from JSON-LD format into a simplified format
1544 * @param array $object
1546 * @return array Questions in a simplified format
1548 private static function processQuestion(array $object): array
1552 if (!empty($object['as:oneOf'])) {
1553 $question['multiple'] = false;
1554 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1555 } elseif (!empty($object['as:anyOf'])) {
1556 $question['multiple'] = true;
1557 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1562 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1563 if (!empty($closed)) {
1564 $question['end-time'] = $closed;
1566 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1569 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1570 $question['options'] = [];
1574 foreach ($options as $option) {
1575 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1579 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1581 if (empty($option['as:replies'])) {
1585 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1587 $question['options'][] = ['name' => $name, 'replies' => $replies];
1589 $voters += (int)$replies;
1592 // For single choice question we can count the number of voters if not provided (like with Misskey)
1593 if (empty($question['voters']) && !$question['multiple']) {
1594 $question['voters'] = $voters;
1601 * Fetch the original source or content with the "language" Markdown or HTML
1603 * @param array $object
1604 * @param array $object_data
1606 * @return array Object data (?)
1607 * @throws \Exception
1609 private static function getSource(array $object, array $object_data): array
1611 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1612 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1613 if (!empty($object_data['source'])) {
1614 return $object_data;
1617 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1618 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1619 if (!empty($object_data['source'])) {
1620 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1621 return $object_data;
1624 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1625 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1626 if (!empty($object_data['source'])) {
1627 $object_data['source'] = HTML::toBBCode($object_data['source']);
1628 return $object_data;
1631 return $object_data;
1635 * Extracts a potential alternate URL from a list of additional URL elements
1637 * @param array $urls
1640 private static function extractAlternateUrl(array $urls): string
1643 foreach ($urls as $key => $url) {
1644 // Not a list but a single URL element
1645 if (!is_numeric($key)) {
1649 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1653 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1658 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1659 if (empty($mediatype)) {
1663 if ($mediatype == 'text/html') {
1664 $alternateUrl = $href;
1668 return $alternateUrl;
1672 * Check if the "as:url" element is an array with multiple links
1673 * This is the case with audio and video posts.
1674 * Then the links are added as attachments
1676 * @param array $urls The object URL list
1677 * @return array an array of attachments
1679 private static function processAttachmentUrls(array $urls): array
1682 foreach ($urls as $key => $url) {
1683 // Not a list but a single URL element
1684 if (!is_numeric($key)) {
1688 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1692 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1697 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1698 if (empty($mediatype)) {
1702 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1704 if ($filetype == 'audio') {
1705 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1706 } elseif ($filetype == 'video') {
1707 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1708 // PeerTube audio-only track
1709 if ($height === 0) {
1713 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1714 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1715 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1716 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1718 // For Torrent links we always store the highest resolution
1719 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1723 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1724 } elseif ($mediatype == 'application/x-mpegURL') {
1725 // PeerTube exception, actual video link is in the tags of this URL element
1726 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1730 return array_values($attachments);
1734 * Fetches data from the object part of an activity
1736 * @param array $object
1738 * @return array|bool Object data or FALSE if $object does not contain @id element
1739 * @throws \Exception
1741 private static function processObject(array $object)
1743 if (!JsonLD::fetchElement($object, '@id')) {
1748 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1749 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1750 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1752 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1753 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1754 $object_data['reply-to-id'] = $object_data['id'];
1756 // On activities the "reply to" is the id of the object it refers to
1757 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1758 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1759 if (!empty($object_id)) {
1760 $object_data['reply-to-id'] = $object_id;
1764 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1765 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1766 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1767 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1768 $object_data['reply-to-id'] = $replyToId;
1772 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1773 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1775 if (empty($object_data['updated'])) {
1776 $object_data['updated'] = $object_data['published'];
1779 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1780 $object_data['published'] = $object_data['updated'];
1783 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1784 if (empty($actor)) {
1785 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1788 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1789 $location = JsonLD::fetchElement($location, 'location', '@value');
1791 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1792 // down to HTML and then finally format to plaintext.
1793 $location = Markdown::convert($location);
1794 $location = BBCode::toPlaintext($location);
1797 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1798 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1799 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1800 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1801 $object_data['actor'] = $object_data['author'] = $actor;
1802 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1803 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1804 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1805 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1806 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1807 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1808 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1809 $object_data = self::getSource($object, $object_data);
1810 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1811 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1812 $object_data['location'] = $location;
1813 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1814 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1815 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1816 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1817 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1818 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1819 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1820 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1821 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1822 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1823 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1825 // Special treatment for Hubzilla links
1826 if (is_array($object_data['alternate-url'])) {
1827 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1829 if (!is_string($object_data['alternate-url'])) {
1830 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1834 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1835 $object_data['alternate-url'] = null;
1838 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1839 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1840 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1843 // For page types we expect that the alternate url posts to some page.
1844 // So we add this to the attachments if it differs from the id.
1845 // Currently only Lemmy is using the page type.
1846 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1847 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1848 $object_data['alternate-url'] = null;
1851 if ($object_data['object_type'] == 'as:Question') {
1852 $object_data['question'] = self::processQuestion($object);
1855 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1856 $receivers = $reception_types = [];
1857 foreach ($receiverdata as $key => $data) {
1858 $receivers[$key] = $data['uid'];
1859 $reception_types[$data['uid']] = $data['type'] ?? 0;
1862 $object_data['receiver_urls'] = self::getReceiverURL($object);
1863 $object_data['receiver'] = $receivers;
1864 $object_data['reception_type'] = $reception_types;
1866 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1867 unset($object_data['receiver'][-1]);
1868 unset($object_data['reception_type'][-1]);
1870 return $object_data;