3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Core\Worker;
33 use Friendica\Model\Contact;
34 use Friendica\Model\APContact;
35 use Friendica\Model\Item;
36 use Friendica\Model\Post;
37 use Friendica\Model\User;
38 use Friendica\Protocol\Activity;
39 use Friendica\Protocol\ActivityPub;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\HTTPSignature;
42 use Friendica\Util\JsonLD;
43 use Friendica\Util\LDSignature;
44 use Friendica\Util\Network;
45 use Friendica\Util\Strings;
48 * ActivityPub Receiver Protocol class
53 * Check what this is meant to do:
62 const PUBLIC_COLLECTION = 'as:Public';
63 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
64 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
65 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
67 const TARGET_UNKNOWN = 0;
72 const TARGET_FOLLOWER = 5;
73 const TARGET_ANSWER = 6;
74 const TARGET_GLOBAL = 7;
76 const COMPLETION_NONE = 0;
77 const COMPLETION_ANNOUCE = 1;
78 const COMPLETION_RELAY = 2;
79 const COMPLETION_MANUAL = 3;
80 const COMPLETION_AUTO = 4;
83 * Checks incoming message from the inbox
85 * @param string $body Body string
86 * @param array $header Header lines
87 * @param integer $uid User ID
91 public static function processInbox(string $body, array $header, int $uid)
93 $activity = json_decode($body, true);
94 if (empty($activity)) {
95 Logger::warning('Invalid body.');
99 $ldactivity = JsonLD::compact($activity);
101 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id') ?? '';
103 $apcontact = APContact::getByURL($actor);
105 if (empty($apcontact)) {
106 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
108 } elseif (APContact::isRelay($apcontact)) {
109 self::processRelayPost($ldactivity, $actor);
112 APContact::unmarkForArchival($apcontact);
115 $http_signer = HTTPSignature::getSigner($body, $header);
116 if ($http_signer === false) {
117 Logger::warning('Invalid HTTP signature, message will be discarded.');
119 } elseif (empty($http_signer)) {
120 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
123 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
126 $signer = [$http_signer];
128 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
130 if (LDSignature::isSigned($activity)) {
131 $ld_signer = LDSignature::getSigner($activity);
132 if (empty($ld_signer)) {
133 Logger::info('Invalid JSON-LD signature from ' . $actor);
134 } elseif ($ld_signer != $http_signer) {
135 $signer[] = $ld_signer;
137 if (!empty($ld_signer && ($actor == $http_signer))) {
138 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
139 $trust_source = true;
140 } elseif (!empty($ld_signer)) {
141 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
142 $trust_source = true;
143 } elseif ($actor == $http_signer) {
144 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
145 $trust_source = true;
147 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
148 $trust_source = false;
150 } elseif ($actor == $http_signer) {
151 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
152 $trust_source = true;
154 Logger::info('No JSON-LD signature, different actor.');
155 $trust_source = false;
158 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
162 * Process incoming posts from relays
164 * @param array $activity
165 * @param string $actor
168 private static function processRelayPost(array $activity, string $actor)
170 $type = JsonLD::fetchElement($activity, '@type');
172 Logger::info('Empty type', ['activity' => $activity, 'actor' => $actor]);
176 if ($type != 'as:Announce') {
177 Logger::info('Not an announcement', ['activity' => $activity, 'actor' => $actor]);
181 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
182 if (empty($object_id)) {
183 Logger::info('No object id found', ['activity' => $activity, 'actor' => $actor]);
187 $contact = Contact::getByURL($actor);
188 if (empty($contact)) {
189 Logger::info('Relay contact not found', ['actor' => $actor]);
193 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
194 Logger::notice('Relay is no sharer', ['actor' => $actor]);
198 Logger::info('Got relayed message id', ['id' => $object_id, 'actor' => $actor]);
200 $item_id = Item::searchByLink($object_id);
202 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
206 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
208 Logger::notice('Relayed message had not been fetched', ['id' => $object_id, 'actor' => $actor]);
214 * Fetches the object type for a given object id
216 * @param array $activity
217 * @param string $object_id Object ID of the the provided object
218 * @param integer $uid User ID
220 * @return string with object type or NULL
221 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
222 * @throws \ImagickException
224 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
226 if (!empty($activity['as:object'])) {
227 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
228 if (!empty($object_type)) {
233 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
234 // We just assume "note" since it doesn't make a difference for the further processing
238 $profile = APContact::getByURL($object_id);
239 if (!empty($profile['type'])) {
240 APContact::unmarkForArchival($profile);
241 return 'as:' . $profile['type'];
244 $data = Processor::fetchCachedActivity($object_id, $uid);
246 $object = JsonLD::compact($data);
247 $type = JsonLD::fetchElement($object, '@type');
257 * Prepare the object array
259 * @param array $activity Array with activity data
260 * @param integer $uid User ID
261 * @param boolean $push Message had been pushed to our system
262 * @param boolean $trust_source Do we trust the source?
264 * @return array with object data
265 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
266 * @throws \ImagickException
268 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
270 $id = JsonLD::fetchElement($activity, '@id');
271 $type = JsonLD::fetchElement($activity, '@type');
272 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
274 if (!empty($object_id) && in_array($type, ['as:Create', 'as:Update'])) {
275 $fetch_id = $object_id;
280 if (!empty($activity['as:object'])) {
281 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
284 if (!empty($id) && !$trust_source) {
285 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
287 $fetched_activity = Processor::fetchCachedActivity($fetch_id, $fetch_uid);
288 if (!empty($fetched_activity)) {
289 $object = JsonLD::compact($fetched_activity);
291 $fetched_id = JsonLD::fetchElement($object, '@id');
292 $fetched_type = JsonLD::fetchElement($object, '@type');
294 if (($fetched_id == $id) && !empty($fetched_type) && ($fetched_type == $type)) {
295 Logger::info('Activity had been fetched successfully', ['id' => $id]);
296 $trust_source = true;
298 } elseif (($fetched_id == $object_id) && !empty($fetched_type) && ($fetched_type == $object_type)) {
299 Logger::info('Fetched data is the object instead of the activity', ['id' => $id]);
300 $trust_source = true;
301 unset($object['@context']);
302 $activity['as:object'] = $object;
304 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
307 Logger::info('Activity could not been fetched', ['id' => $id]);
311 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
313 Logger::info('Empty actor', ['activity' => $activity]);
317 $type = JsonLD::fetchElement($activity, '@type');
319 // Fetch all receivers from to, cc, bto and bcc
320 $receiverdata = self::getReceivers($activity, $actor);
321 $receivers = $reception_types = [];
322 foreach ($receiverdata as $key => $data) {
323 $receivers[$key] = $data['uid'];
324 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
327 $urls = self::getReceiverURL($activity);
329 // When it is a delivery to a personal inbox we add that user to the receivers
331 $additional = [$uid => $uid];
332 $receivers = array_replace($receivers, $additional);
333 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]))) {
334 $reception_types[$uid] = self::TARGET_BCC;
335 $owner = User::getOwnerDataById($uid);
336 if (!empty($owner['url'])) {
337 $urls['as:bcc'][] = $owner['url'];
342 // We possibly need some user to fetch private content,
343 // so we fetch one out of the receivers if no uid is provided.
344 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
346 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
347 if (empty($object_id)) {
348 Logger::info('No object found');
352 if (!is_string($object_id)) {
353 Logger::info('Invalid object id', ['object' => $object_id]);
357 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
359 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
360 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
361 $data = Processor::fetchCachedActivity($object_id, $fetch_uid);
363 $type = $object_type;
364 $activity = JsonLD::compact($data);
366 // Some variables need to be refetched since the activity changed
367 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
368 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
369 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
373 // Any activities on account types must not be altered
374 if (in_array($object_type, self::ACCOUNT_TYPES)) {
376 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
377 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
378 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
379 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
380 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
381 $object_data['push'] = $push;
382 if (!$trust_source && ($type == 'as:Delete')) {
383 $apcontact = APContact::getByURL($object_data['object_id'], true);
384 $trust_source = empty($apcontact) || ($apcontact['type'] == 'Tombstone') || $apcontact['suspended'];
386 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
387 // Fetch the content only on activities where this matters
388 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
389 // Always fetch on "Announce"
390 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
391 if (empty($object_data)) {
392 Logger::info("Object data couldn't be processed");
396 $object_data['object_id'] = $object_id;
398 if ($type == 'as:Announce') {
399 $object_data['push'] = false;
401 $object_data['push'] = $push;
404 // Test if it is an answer to a mail
405 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
406 $object_data['directmessage'] = true;
408 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
410 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
411 // Create a mostly empty array out of the activity data (instead of the object).
412 // This way we later don't have to check for the existence of each individual array element.
413 $object_data = self::processObject($activity);
414 $object_data['name'] = $type;
415 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
416 $object_data['object_id'] = $object_id;
417 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
418 $object_data['push'] = $push;
419 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
421 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
422 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
423 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
424 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
425 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
426 $object_data['push'] = $push;
429 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
430 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
431 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
432 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
433 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
434 $object_data['push'] = $push;
436 // An Undo is done on the object of an object, so we need that type as well
437 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
438 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
441 if (!$trust_source && ($type == 'as:Delete') && in_array($object_data['object_type'], array_merge(['as:Tombstone', ''], self::CONTENT_TYPES))) {
442 $trust_source = Processor::isActivityGone($object_data['object_id']);
443 if (!$trust_source) {
444 $trust_source = !empty(APContact::getByURL($object_data['object_id'], false));
449 $object_data = self::addActivityFields($object_data, $activity);
451 if (empty($object_data['object_type'])) {
452 $object_data['object_type'] = $object_type;
455 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
456 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
457 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
461 $object_data['type'] = $type;
462 $object_data['actor'] = $actor;
463 $object_data['item_receiver'] = $receivers;
464 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
465 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
467 // This check here interferes with Hubzilla posts where the author host differs from the host the post was created
468 // $author = $object_data['author'] ?? $actor;
469 // if (!empty($author) && !empty($object_data['id'])) {
470 // $author_host = parse_url($author, PHP_URL_HOST);
471 // $id_host = parse_url($object_data['id'], PHP_URL_HOST);
472 // if ($author_host == $id_host) {
473 // Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
475 // Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
476 // $trust_source = false;
480 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
486 * Fetches the first user id from the receiver array
488 * @param array $receivers Array with receivers
489 * @return integer user id;
491 public static function getFirstUserFromReceivers(array $receivers): int
493 foreach ($receivers as $receiver) {
494 if (!empty($receiver)) {
502 * Processes the activity object
504 * @param array $activity Array with activity data
505 * @param string $body The unprocessed body
506 * @param int|null $uid User ID
507 * @param boolean $trust_source Do we trust the source?
508 * @param boolean $push Message had been pushed to our system
509 * @param array $signer The signer of the post
513 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
514 * @throws \ImagickException
516 public static function processActivity(array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '', int $completion = Receiver::COMPLETION_AUTO): bool
518 $type = JsonLD::fetchElement($activity, '@type');
520 Logger::info('Empty type', ['activity' => $activity]);
524 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
525 Logger::info('Empty object', ['activity' => $activity]);
529 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
531 Logger::info('Empty actor', ['activity' => $activity]);
535 if (is_array($activity['as:object'])) {
536 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
541 // Test the provided signatures against the actor and "attributedTo"
543 if (!empty($attributed_to) && !empty($actor)) {
544 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
546 $trust_source = in_array($actor, $signer);
550 // $trust_source is called by reference and is set to true if the content was retrieved successfully
551 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
552 if (empty($object_data)) {
553 Logger::info('No object data found', ['activity' => $activity]);
557 // Lemmy is announcing activities.
558 // We are changing the announces into regular activities.
559 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
560 $type = $object_data['type'];
563 if (!empty($body) && empty($object_data['raw'])) {
564 $object_data['raw'] = $body;
567 // Internal flag for thread completion. See Processor.php
568 if (!empty($activity['thread-completion'])) {
569 $object_data['thread-completion'] = $activity['thread-completion'];
572 if (!empty($activity['completion-mode'])) {
573 $object_data['completion-mode'] = $activity['completion-mode'];
576 if (!empty($activity['thread-children-type'])) {
577 $object_data['thread-children-type'] = $activity['thread-children-type'];
580 // Internal flag for posts that arrived via relay
581 if (!empty($activity['from-relay'])) {
582 $object_data['from-relay'] = $activity['from-relay'];
585 if ($type == 'as:Announce') {
586 $object_data['object_activity'] = $activity;
589 if (($type == 'as:Create') && Queue::exists($object_data['object_id'], $type)) {
590 Logger::info('The activity is already added.', ['id' => $object_data['object_id']]);
594 if (DI::config()->get('system', 'decoupled_receiver') && ($trust_source || DI::config()->get('debug', 'ap_inbox_store_untrusted'))) {
595 $object_data = Queue::add($object_data, $type, $uid, $http_signer, $push, $trust_source);
598 if (!$trust_source) {
599 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
603 if (!empty($object_data['entry-id']) && DI::config()->get('system', 'decoupled_receiver') && ($push || ($completion == self::COMPLETION_RELAY))) {
604 // We delay by 5 seconds to allow to accumulate all receivers
605 $delayed = date(DateTimeFormat::MYSQL, time() + 5);
606 Logger::debug('Initiate processing', ['id' => $object_data['entry-id'], 'uri' => $object_data['object_id']]);
607 $wid = Worker::add(['priority' => PRIORITY_HIGH, 'delayed' => $delayed], 'ProcessQueue', $object_data['entry-id']);
608 Queue::setWorkerId($object_data['entry-id'], $wid);
612 if (!empty($activity['recursion-depth'])) {
613 $object_data['recursion-depth'] = $activity['recursion-depth'];
616 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
617 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
620 if (!self::routeActivities($object_data, $type, $push)) {
621 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
622 Queue::remove($object_data);
630 * @param array $object_data
631 * @param string $type
633 * @param bool $fetch_parents
635 * @return boolean Could the activity be routed?
637 public static function routeActivities(array $object_data, string $type, bool $push, bool $fetch_parents = true): bool
639 $activity = $object_data['object_activity'] ?? [];
643 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
644 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
645 ActivityPub\Processor::postItem($object_data, $item);
646 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
647 // Unhandled Peertube activity
648 Queue::remove($object_data);
655 if (in_array($object_data['object_type'], ['as:Event'])) {
656 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
657 ActivityPub\Processor::postItem($object_data, $item);
664 if ($object_data['object_type'] == 'as:tag') {
665 ActivityPub\Processor::addTag($object_data);
666 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
667 ActivityPub\Processor::addToFeaturedCollection($object_data);
668 } elseif ($object_data['object_type'] == '') {
669 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
670 Queue::remove($object_data);
677 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
678 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
679 $object_data['thread-completion'] = Contact::getIdForURL($actor);
680 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
682 $item = ActivityPub\Processor::createItem($object_data, $fetch_parents);
687 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
688 ActivityPub\Processor::postItem($object_data, $item);
690 if (!empty($activity)) {
691 $announce_object_data = self::processObject($activity);
692 $announce_object_data['name'] = $type;
693 $announce_object_data['author'] = $actor;
694 $announce_object_data['object_id'] = $object_data['object_id'];
695 $announce_object_data['object_type'] = $object_data['object_type'];
696 $announce_object_data['push'] = $push;
698 if (!empty($object_data['raw'])) {
699 $announce_object_data['raw'] = $object_data['raw'];
701 if (!empty($object_data['raw-object'])) {
702 $announce_object_data['raw-object'] = $object_data['raw-object'];
704 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
712 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
713 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
714 } elseif ($object_data['object_type'] == '') {
715 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
716 Queue::remove($object_data);
723 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
724 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
725 } elseif ($object_data['object_type'] == '') {
726 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
727 Queue::remove($object_data);
733 case 'as:TentativeAccept':
734 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
735 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
742 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
743 ActivityPub\Processor::updateItem($object_data);
744 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
745 ActivityPub\Processor::updatePerson($object_data);
746 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
747 // Unhandled Peertube activity
748 Queue::remove($object_data);
755 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
756 ActivityPub\Processor::deleteItem($object_data);
757 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
758 ActivityPub\Processor::deletePerson($object_data);
759 } elseif ($object_data['object_type'] == '') {
760 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
761 Queue::remove($object_data);
768 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
769 ActivityPub\Processor::blockAccount($object_data);
776 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
777 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
778 } elseif ($object_data['object_type'] == '') {
779 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
780 Queue::remove($object_data);
787 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
788 ActivityPub\Processor::followUser($object_data);
789 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
790 $object_data['reply-to-id'] = $object_data['object_id'];
791 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
798 if ($object_data['object_type'] == 'as:Follow') {
799 ActivityPub\Processor::acceptFollowUser($object_data);
800 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
801 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
808 if ($object_data['object_type'] == 'as:Follow') {
809 ActivityPub\Processor::rejectFollowUser($object_data);
810 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
811 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
818 if (($object_data['object_type'] == 'as:Follow') &&
819 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
820 ActivityPub\Processor::undoFollowUser($object_data);
821 } elseif (($object_data['object_type'] == 'as:Follow') &&
822 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
823 ActivityPub\Processor::undoActivity($object_data);
824 } elseif (($object_data['object_type'] == 'as:Accept') &&
825 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
826 ActivityPub\Processor::rejectFollowUser($object_data);
827 } elseif (($object_data['object_type'] == 'as:Block') &&
828 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
829 ActivityPub\Processor::unblockAccount($object_data);
830 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
831 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
832 ActivityPub\Processor::undoActivity($object_data);
833 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
834 empty($object_data['object_object_type'])) {
835 // We cannot detect the target object. So we can ignore it.
836 Queue::remove($object_data);
837 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
838 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
839 // Unhandled Peertube activity
840 Queue::remove($object_data);
847 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
848 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
849 } elseif ($object_data['object_type'] == '') {
850 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
851 Queue::remove($object_data);
857 case 'litepub:EmojiReact':
858 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
859 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
860 } elseif ($object_data['object_type'] == '') {
861 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
862 Queue::remove($object_data);
869 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
876 * Stores unhandled or unknown Activities as a file
878 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
879 * @param string $type Activity type
880 * @param array $object_data Preprocessed array that is generated out of the received activity
881 * @param array $activity Array with activity data
882 * @param string $body The unprocessed body
883 * @param integer $uid User ID
884 * @param boolean $trust_source Do we trust the source?
885 * @param boolean $push Message had been pushed to our system
886 * @param array $signer The signer of the post
889 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 = [])
891 if (!DI::config()->get('debug', 'ap_log_unknown')) {
895 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
897 if (!empty($object_data['object_type'])) {
898 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
901 if (!empty($object_data['object_object_type'])) {
902 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
905 $tempfile = tempnam(System::getTempPath(), $file);
906 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));
907 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
911 * Fetch a user id from an activity array
913 * @param array $activity
914 * @param string $actor
916 * @return int user id
918 public static function getBestUserForActivity(array $activity): int
921 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
923 $receivers = self::getReceivers($activity, $actor);
924 foreach ($receivers as $receiver) {
925 if ($receiver['type'] == self::TARGET_GLOBAL) {
928 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
929 $uid = $receiver['uid'];
933 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
935 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
936 if (!empty($contact['uid'])) {
937 $uid = $contact['uid'];
944 // @TODO Missing documentation
945 public static function getReceiverURL(array $activity): array
949 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
950 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
951 if (empty($receiver_list)) {
955 foreach ($receiver_list as $receiver) {
956 if ($receiver == self::PUBLIC_COLLECTION) {
957 $receiver = ActivityPub::PUBLIC_COLLECTION;
959 $urls[$element][] = $receiver;
967 * Fetch the receiver list from an activity array
969 * @param array $activity
970 * @param string $actor
972 * @param boolean $fetch_unlisted
974 * @return array with receivers (user id)
977 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
979 $reply = $receivers = $profile = [];
981 // When it is an answer, we inherite the receivers from the parent
982 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
983 if (!empty($replyto)) {
986 // Fix possibly wrong item URI (could be an answer to a plink uri)
987 $fixedReplyTo = Item::getURIByLink($replyto);
988 if (!empty($fixedReplyTo)) {
989 $reply[] = $fixedReplyTo;
993 // Fetch all posts that refer to the object id
994 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
995 if (!empty($object_id)) {
996 $reply[] = $object_id;
999 if (!empty($reply)) {
1000 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1001 while ($parent = Post::fetch($parents)) {
1002 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1004 DBA::close($parents);
1007 if (!empty($actor)) {
1008 $profile = APContact::getByURL($actor);
1009 $followers = $profile['followers'] ?? '';
1010 $is_forum = ($actor['type'] ?? '') == 'Group';
1011 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1013 Logger::info('Empty actor', ['activity' => $activity]);
1018 // We have to prevent false follower assumptions upon thread completions
1019 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1021 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1022 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1023 if (empty($receiver_list)) {
1027 foreach ($receiver_list as $receiver) {
1028 if ($receiver == self::PUBLIC_COLLECTION) {
1029 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1032 // Add receiver "-1" for unlisted posts
1033 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1034 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1037 // Fetch the receivers for the public and the followers collection
1038 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1039 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1043 // Fetching all directly addressed receivers
1044 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1045 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1046 if (!DBA::isResult($contact)) {
1050 // Check if the potential receiver is following the actor
1051 // Exception: The receiver is targetted via "to" or this is a comment
1052 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1053 $networks = Protocol::FEDERATED;
1054 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1055 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1057 // Forum posts are only accepted from forum contacts
1058 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1059 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1062 if (!DBA::exists('contact', $condition)) {
1067 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1068 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1071 $type = self::TARGET_TO;
1074 $type = self::TARGET_CC;
1077 $type = self::TARGET_BTO;
1080 $type = self::TARGET_BCC;
1084 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1089 self::switchContacts($receivers, $actor);
1095 * Fetch the receiver list of a given actor
1097 * @param string $actor
1098 * @param array $tags
1099 * @param array $receivers
1100 * @param integer $target_type
1101 * @param array $profile
1103 * @return array with receivers (user id)
1104 * @throws \Exception
1106 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1108 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1109 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1111 if (!empty($profile['uri-id'])) {
1112 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1113 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1114 while ($contact = DBA::fetch($contacts)) {
1115 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1116 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1119 DBA::close($contacts);
1121 // This part will only be called while post update 1426 wasn't finished
1122 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1123 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1124 while ($contact = DBA::fetch($contacts)) {
1125 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1126 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1129 DBA::close($contacts);
1131 // The queries are split because of performance issues
1132 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1133 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1134 while ($contact = DBA::fetch($contacts)) {
1135 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1136 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1139 DBA::close($contacts);
1145 * Tests if the contact is a valid receiver for this actor
1147 * @param array $contact
1148 * @param array $tags
1150 * @return bool with receivers (user id)
1151 * @throws \Exception
1153 private static function isValidReceiverForActor(array $contact, array $tags): bool
1155 // Are we following the contact? Then this is a valid receiver
1156 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1160 // When the possible receiver isn't a community, then it is no valid receiver
1161 $owner = User::getOwnerDataById($contact['uid']);
1162 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1166 // Is the community account tagged?
1167 foreach ($tags as $tag) {
1168 if ($tag['type'] != 'Mention') {
1172 if (Strings::compareLink($tag['href'], $owner['url'])) {
1181 * Switches existing contacts to ActivityPub
1183 * @param integer $cid Contact ID
1184 * @param integer $uid User ID
1185 * @param string $url Profile URL
1187 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1188 * @throws \ImagickException
1190 public static function switchContact(int $cid, int $uid, string $url)
1192 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1193 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1197 if (Contact::updateFromProbe($cid)) {
1198 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1201 // Send a new follow request to be sure that the connection still exists
1202 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1203 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1204 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1209 * @TODO Fix documentation and type-hints
1214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1215 * @throws \ImagickException
1217 private static function switchContacts($receivers, $actor)
1219 if (empty($actor)) {
1223 foreach ($receivers as $receiver) {
1224 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1225 if (DBA::isResult($contact)) {
1226 self::switchContact($contact['id'], $receiver['uid'], $actor);
1229 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1230 if (DBA::isResult($contact)) {
1231 self::switchContact($contact['id'], $receiver['uid'], $actor);
1237 * @TODO Fix documentation and type-hints
1239 * @param $object_data
1240 * @param array $activity
1244 private static function addActivityFields($object_data, array $activity)
1246 if (!empty($activity['published']) && empty($object_data['published'])) {
1247 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1250 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1251 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1254 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1255 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1257 if (!empty($object_data['object_id'])) {
1258 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1259 $objectId = Item::getURIByLink($object_data['object_id']);
1260 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1261 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1262 $object_data['object_id'] = $objectId;
1266 return $object_data;
1270 * Fetches the object data from external ressources if needed
1272 * @param string $object_id Object ID of the the provided object
1273 * @param array $object The provided object array
1274 * @param boolean $trust_source Do we trust the provided object?
1275 * @param integer $uid User ID for the signature that we use to fetch data
1277 * @return array|false with trusted and valid object data
1278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1279 * @throws \ImagickException
1281 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1283 // By fetching the type we check if the object is complete.
1284 $type = JsonLD::fetchElement($object, '@type');
1286 if (!$trust_source || empty($type)) {
1287 $data = Processor::fetchCachedActivity($object_id, $uid);
1288 if (!empty($data)) {
1289 $object = JsonLD::compact($data);
1290 Logger::info('Fetched content for ' . $object_id);
1292 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1294 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1295 if (!DBA::isResult($item)) {
1296 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1299 Logger::info('Using already stored item for url ' . $object_id);
1300 $data = ActivityPub\Transmitter::createNote($item);
1301 $object = JsonLD::compact($data);
1304 $id = JsonLD::fetchElement($object, '@id');
1306 Logger::info('Empty id');
1310 if ($id != $object_id) {
1311 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1315 Logger::info('Using original object for url ' . $object_id);
1318 $type = JsonLD::fetchElement($object, '@type');
1320 Logger::info('Empty type');
1324 // Lemmy is resharing "create" activities instead of content
1325 // We fetch the content from the activity.
1326 if (in_array($type, ['as:Create'])) {
1327 $object = $object['as:object'];
1328 $type = JsonLD::fetchElement($object, '@type');
1330 Logger::info('Empty type');
1333 $object_data = self::processObject($object);
1336 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1337 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1338 $object_data = self::processObject($object);
1340 if (!empty($data)) {
1341 $object_data['raw-object'] = json_encode($data);
1343 return $object_data;
1346 if ($type == 'as:Announce') {
1347 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1348 if (empty($object_id) || !is_string($object_id)) {
1351 return self::fetchObject($object_id, [], false, $uid);
1354 Logger::info('Unhandled object type: ' . $type);
1359 * Converts the language element (Used by Peertube)
1361 * @param array $languages
1362 * @return array Languages
1364 public static function processLanguages(array $languages): array
1366 if (empty($languages)) {
1370 $language_list = [];
1372 foreach ($languages as $language) {
1373 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1374 $language_list[$language['_:identifier']] = $language['as:name'];
1377 return $language_list;
1381 * Convert tags from JSON-LD format into a simplified format
1383 * @param array $tags Tags in JSON-LD format
1385 * @return array with tags in a simplified format
1387 public static function processTags(array $tags): array
1391 foreach ($tags as $tag) {
1396 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1397 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1398 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1400 if (empty($element['type'])) {
1404 if (empty($element['href'])) {
1405 $element['href'] = $element['name'];
1408 $taglist[] = $element;
1414 * Convert emojis from JSON-LD format into a simplified format
1416 * @param array $emojis
1417 * @return array with emojis in a simplified format
1419 private static function processEmojis(array $emojis): array
1423 foreach ($emojis as $emoji) {
1424 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1428 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1429 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1432 $emojilist[] = $element;
1439 * Convert attachments from JSON-LD format into a simplified format
1441 * @param array $attachments Attachments in JSON-LD format
1443 * @return array Attachments in a simplified format
1445 private static function processAttachments(array $attachments): array
1449 // Removes empty values
1450 $attachments = array_filter($attachments);
1452 foreach ($attachments as $attachment) {
1453 switch (JsonLD::fetchElement($attachment, '@type')) {
1458 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1459 foreach ($urls as $url) {
1460 // Single scalar URL case
1461 if (is_string($url)) {
1466 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1467 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1468 if (Strings::startsWith($mediaType, 'image')) {
1477 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1478 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1480 'image' => $pageImage,
1484 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1485 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1486 $imagePreviewUrl = null;
1488 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1489 $imageVariants = [];
1490 $previewVariants = [];
1491 foreach ($urls as $url) {
1492 // Scalar URL, no discrimination possible
1493 if (is_string($url)) {
1494 $imageFullUrl = $url;
1498 // Not sure what to do with a different Link media type than the base Image, we skip
1499 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1503 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1505 // Default URL choice if no discriminating width is provided
1506 $imageFullUrl = $href ?? $imageFullUrl;
1508 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1510 if ($href && $width) {
1511 $imageVariants[$width] = $href;
1512 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1513 $previewVariants[abs(632 - $width)] = $href;
1517 if ($imageVariants) {
1518 // Taking the maximum size image
1519 ksort($imageVariants);
1520 $imageFullUrl = array_pop($imageVariants);
1522 // Taking the minimum number distance to the target distance
1523 ksort($previewVariants);
1524 $imagePreviewUrl = array_shift($previewVariants);
1527 unset($imageVariants);
1528 unset($previewVariants);
1532 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1533 'mediaType' => $mediaType,
1534 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1535 'url' => $imageFullUrl,
1536 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1541 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1542 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1543 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1544 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1545 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1546 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1547 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1556 * Convert questions from JSON-LD format into a simplified format
1558 * @param array $object
1560 * @return array Questions in a simplified format
1562 private static function processQuestion(array $object): array
1566 if (!empty($object['as:oneOf'])) {
1567 $question['multiple'] = false;
1568 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1569 } elseif (!empty($object['as:anyOf'])) {
1570 $question['multiple'] = true;
1571 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1576 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1577 if (!empty($closed)) {
1578 $question['end-time'] = $closed;
1580 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1583 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1584 $question['options'] = [];
1588 foreach ($options as $option) {
1589 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1593 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1595 if (empty($option['as:replies'])) {
1599 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1601 $question['options'][] = ['name' => $name, 'replies' => $replies];
1603 $voters += (int)$replies;
1606 // For single choice question we can count the number of voters if not provided (like with Misskey)
1607 if (empty($question['voters']) && !$question['multiple']) {
1608 $question['voters'] = $voters;
1615 * Fetch the original source or content with the "language" Markdown or HTML
1617 * @param array $object
1618 * @param array $object_data
1620 * @return array Object data (?)
1621 * @throws \Exception
1623 private static function getSource(array $object, array $object_data): array
1625 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1626 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1627 if (!empty($object_data['source'])) {
1628 return $object_data;
1631 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1632 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1633 if (!empty($object_data['source'])) {
1634 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1635 return $object_data;
1638 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1639 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1640 if (!empty($object_data['source'])) {
1641 $object_data['source'] = HTML::toBBCode($object_data['source']);
1642 return $object_data;
1645 return $object_data;
1649 * Extracts a potential alternate URL from a list of additional URL elements
1651 * @param array $urls
1654 private static function extractAlternateUrl(array $urls): string
1657 foreach ($urls as $key => $url) {
1658 // Not a list but a single URL element
1659 if (!is_numeric($key)) {
1663 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1667 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1672 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1673 if (empty($mediatype)) {
1677 if ($mediatype == 'text/html') {
1678 $alternateUrl = $href;
1682 return $alternateUrl;
1686 * Check if the "as:url" element is an array with multiple links
1687 * This is the case with audio and video posts.
1688 * Then the links are added as attachments
1690 * @param array $urls The object URL list
1691 * @return array an array of attachments
1693 private static function processAttachmentUrls(array $urls): array
1696 foreach ($urls as $key => $url) {
1697 // Not a list but a single URL element
1698 if (!is_numeric($key)) {
1702 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1706 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1711 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1712 if (empty($mediatype)) {
1716 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1718 if ($filetype == 'audio') {
1719 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1720 } elseif ($filetype == 'video') {
1721 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1722 // PeerTube audio-only track
1723 if ($height === 0) {
1727 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1728 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1729 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1730 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1732 // For Torrent links we always store the highest resolution
1733 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1737 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1738 } elseif ($mediatype == 'application/x-mpegURL') {
1739 // PeerTube exception, actual video link is in the tags of this URL element
1740 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1744 return array_values($attachments);
1748 * Fetches data from the object part of an activity
1750 * @param array $object
1752 * @return array|bool Object data or FALSE if $object does not contain @id element
1753 * @throws \Exception
1755 private static function processObject(array $object)
1757 if (!JsonLD::fetchElement($object, '@id')) {
1762 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1763 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1764 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1766 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1767 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1768 $object_data['reply-to-id'] = $object_data['id'];
1770 // On activities the "reply to" is the id of the object it refers to
1771 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1772 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1773 if (!empty($object_id)) {
1774 $object_data['reply-to-id'] = $object_id;
1778 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1779 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1780 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1781 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1782 $object_data['reply-to-id'] = $replyToId;
1786 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1787 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1789 if (empty($object_data['updated'])) {
1790 $object_data['updated'] = $object_data['published'];
1793 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1794 $object_data['published'] = $object_data['updated'];
1797 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1798 if (empty($actor)) {
1799 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1802 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1803 $location = JsonLD::fetchElement($location, 'location', '@value');
1805 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1806 // down to HTML and then finally format to plaintext.
1807 $location = Markdown::convert($location);
1808 $location = BBCode::toPlaintext($location);
1811 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1812 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1813 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1814 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1815 $object_data['actor'] = $object_data['author'] = $actor;
1816 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1817 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1818 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1819 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1820 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1821 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1822 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1823 $object_data = self::getSource($object, $object_data);
1824 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1825 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1826 $object_data['location'] = $location;
1827 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1828 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1829 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1830 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1831 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1832 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1833 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1834 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1835 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1836 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1837 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1839 // Special treatment for Hubzilla links
1840 if (is_array($object_data['alternate-url'])) {
1841 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1843 if (!is_string($object_data['alternate-url'])) {
1844 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1848 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1849 $object_data['alternate-url'] = null;
1852 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1853 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1854 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1857 // For page types we expect that the alternate url posts to some page.
1858 // So we add this to the attachments if it differs from the id.
1859 // Currently only Lemmy is using the page type.
1860 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1861 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1862 $object_data['alternate-url'] = null;
1865 if ($object_data['object_type'] == 'as:Question') {
1866 $object_data['question'] = self::processQuestion($object);
1869 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1870 $receivers = $reception_types = [];
1871 foreach ($receiverdata as $key => $data) {
1872 $receivers[$key] = $data['uid'];
1873 $reception_types[$data['uid']] = $data['type'] ?? 0;
1876 $object_data['receiver_urls'] = self::getReceiverURL($object);
1877 $object_data['receiver'] = $receivers;
1878 $object_data['reception_type'] = $reception_types;
1880 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1881 unset($object_data['receiver'][-1]);
1882 unset($object_data['reception_type'][-1]);
1884 return $object_data;