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
632 * @param boolean $push
634 * @return boolean Could the activity be routed?
636 public static function routeActivities(array $object_data, string $type, bool $push): bool
638 $activity = $object_data['object_activity'] ?? [];
642 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
643 $item = ActivityPub\Processor::createItem($object_data);
644 ActivityPub\Processor::postItem($object_data, $item);
645 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
646 // Unhandled Peertube activity
647 Queue::remove($object_data);
654 if (in_array($object_data['object_type'], ['as:Event'])) {
655 $item = ActivityPub\Processor::createItem($object_data);
656 ActivityPub\Processor::postItem($object_data, $item);
663 if ($object_data['object_type'] == 'as:tag') {
664 ActivityPub\Processor::addTag($object_data);
665 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
666 ActivityPub\Processor::addToFeaturedCollection($object_data);
667 } elseif ($object_data['object_type'] == '') {
668 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
669 Queue::remove($object_data);
676 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
677 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
678 $object_data['thread-completion'] = Contact::getIdForURL($actor);
679 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
681 $item = ActivityPub\Processor::createItem($object_data);
686 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
687 ActivityPub\Processor::postItem($object_data, $item);
689 if (!empty($activity)) {
690 $announce_object_data = self::processObject($activity);
691 $announce_object_data['name'] = $type;
692 $announce_object_data['author'] = $actor;
693 $announce_object_data['object_id'] = $object_data['object_id'];
694 $announce_object_data['object_type'] = $object_data['object_type'];
695 $announce_object_data['push'] = $push;
697 if (!empty($object_data['raw'])) {
698 $announce_object_data['raw'] = $object_data['raw'];
700 if (!empty($object_data['raw-object'])) {
701 $announce_object_data['raw-object'] = $object_data['raw-object'];
703 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
711 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
712 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
713 } elseif ($object_data['object_type'] == '') {
714 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
715 Queue::remove($object_data);
722 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
723 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
724 } elseif ($object_data['object_type'] == '') {
725 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
726 Queue::remove($object_data);
732 case 'as:TentativeAccept':
733 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
734 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
741 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
742 ActivityPub\Processor::updateItem($object_data);
743 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
744 ActivityPub\Processor::updatePerson($object_data);
745 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
746 // Unhandled Peertube activity
747 Queue::remove($object_data);
754 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
755 ActivityPub\Processor::deleteItem($object_data);
756 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
757 ActivityPub\Processor::deletePerson($object_data);
758 } elseif ($object_data['object_type'] == '') {
759 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
760 Queue::remove($object_data);
767 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
768 ActivityPub\Processor::blockAccount($object_data);
775 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
776 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
777 } elseif ($object_data['object_type'] == '') {
778 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
779 Queue::remove($object_data);
786 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
787 ActivityPub\Processor::followUser($object_data);
788 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
789 $object_data['reply-to-id'] = $object_data['object_id'];
790 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
797 if ($object_data['object_type'] == 'as:Follow') {
798 ActivityPub\Processor::acceptFollowUser($object_data);
799 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
800 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
807 if ($object_data['object_type'] == 'as:Follow') {
808 ActivityPub\Processor::rejectFollowUser($object_data);
809 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
810 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
817 if (($object_data['object_type'] == 'as:Follow') &&
818 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
819 ActivityPub\Processor::undoFollowUser($object_data);
820 } elseif (($object_data['object_type'] == 'as:Follow') &&
821 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
822 ActivityPub\Processor::undoActivity($object_data);
823 } elseif (($object_data['object_type'] == 'as:Accept') &&
824 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
825 ActivityPub\Processor::rejectFollowUser($object_data);
826 } elseif (($object_data['object_type'] == 'as:Block') &&
827 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
828 ActivityPub\Processor::unblockAccount($object_data);
829 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
830 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
831 ActivityPub\Processor::undoActivity($object_data);
832 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
833 empty($object_data['object_object_type'])) {
834 // We cannot detect the target object. So we can ignore it.
835 Queue::remove($object_data);
836 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
837 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
838 // Unhandled Peertube activity
839 Queue::remove($object_data);
846 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
847 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
848 } elseif ($object_data['object_type'] == '') {
849 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
850 Queue::remove($object_data);
856 case 'litepub:EmojiReact':
857 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
858 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
859 } elseif ($object_data['object_type'] == '') {
860 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
861 Queue::remove($object_data);
868 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
875 * Stores unhandled or unknown Activities as a file
877 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
878 * @param string $type Activity type
879 * @param array $object_data Preprocessed array that is generated out of the received activity
880 * @param array $activity Array with activity data
881 * @param string $body The unprocessed body
882 * @param integer $uid User ID
883 * @param boolean $trust_source Do we trust the source?
884 * @param boolean $push Message had been pushed to our system
885 * @param array $signer The signer of the post
888 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 = [])
890 if (!DI::config()->get('debug', 'ap_log_unknown')) {
894 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
896 if (!empty($object_data['object_type'])) {
897 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
900 if (!empty($object_data['object_object_type'])) {
901 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
904 $tempfile = tempnam(System::getTempPath(), $file);
905 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));
906 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
910 * Fetch a user id from an activity array
912 * @param array $activity
913 * @param string $actor
915 * @return int user id
917 public static function getBestUserForActivity(array $activity): int
920 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
922 $receivers = self::getReceivers($activity, $actor);
923 foreach ($receivers as $receiver) {
924 if ($receiver['type'] == self::TARGET_GLOBAL) {
927 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
928 $uid = $receiver['uid'];
932 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
934 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
935 if (!empty($contact['uid'])) {
936 $uid = $contact['uid'];
943 // @TODO Missing documentation
944 public static function getReceiverURL(array $activity): array
948 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
949 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
950 if (empty($receiver_list)) {
954 foreach ($receiver_list as $receiver) {
955 if ($receiver == self::PUBLIC_COLLECTION) {
956 $receiver = ActivityPub::PUBLIC_COLLECTION;
958 $urls[$element][] = $receiver;
966 * Fetch the receiver list from an activity array
968 * @param array $activity
969 * @param string $actor
971 * @param boolean $fetch_unlisted
973 * @return array with receivers (user id)
976 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
978 $reply = $receivers = $profile = [];
980 // When it is an answer, we inherite the receivers from the parent
981 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
982 if (!empty($replyto)) {
985 // Fix possibly wrong item URI (could be an answer to a plink uri)
986 $fixedReplyTo = Item::getURIByLink($replyto);
987 if (!empty($fixedReplyTo)) {
988 $reply[] = $fixedReplyTo;
992 // Fetch all posts that refer to the object id
993 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
994 if (!empty($object_id)) {
995 $reply[] = $object_id;
998 if (!empty($reply)) {
999 $parents = Post::select(['uid'], DBA::mergeConditions(['uri' => $reply], ["`uid` != ?", 0]));
1000 while ($parent = Post::fetch($parents)) {
1001 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
1003 DBA::close($parents);
1006 if (!empty($actor)) {
1007 $profile = APContact::getByURL($actor);
1008 $followers = $profile['followers'] ?? '';
1009 $is_forum = ($actor['type'] ?? '') == 'Group';
1010 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
1012 Logger::info('Empty actor', ['activity' => $activity]);
1017 // We have to prevent false follower assumptions upon thread completions
1018 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
1020 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
1021 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
1022 if (empty($receiver_list)) {
1026 foreach ($receiver_list as $receiver) {
1027 if ($receiver == self::PUBLIC_COLLECTION) {
1028 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
1031 // Add receiver "-1" for unlisted posts
1032 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
1033 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
1036 // Fetch the receivers for the public and the followers collection
1037 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
1038 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1042 // Fetching all directly addressed receivers
1043 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1044 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1045 if (!DBA::isResult($contact)) {
1049 // Check if the potential receiver is following the actor
1050 // Exception: The receiver is targetted via "to" or this is a comment
1051 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1052 $networks = Protocol::FEDERATED;
1053 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1054 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1056 // Forum posts are only accepted from forum contacts
1057 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1058 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1061 if (!DBA::exists('contact', $condition)) {
1066 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1067 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1070 $type = self::TARGET_TO;
1073 $type = self::TARGET_CC;
1076 $type = self::TARGET_BTO;
1079 $type = self::TARGET_BCC;
1083 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1088 self::switchContacts($receivers, $actor);
1094 * Fetch the receiver list of a given actor
1096 * @param string $actor
1097 * @param array $tags
1098 * @param array $receivers
1099 * @param integer $target_type
1100 * @param array $profile
1102 * @return array with receivers (user id)
1103 * @throws \Exception
1105 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1107 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1108 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1110 if (!empty($profile['uri-id'])) {
1111 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1112 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1113 while ($contact = DBA::fetch($contacts)) {
1114 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1115 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1118 DBA::close($contacts);
1120 // This part will only be called while post update 1426 wasn't finished
1121 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1122 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1123 while ($contact = DBA::fetch($contacts)) {
1124 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1125 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1128 DBA::close($contacts);
1130 // The queries are split because of performance issues
1131 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1132 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1133 while ($contact = DBA::fetch($contacts)) {
1134 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1135 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1138 DBA::close($contacts);
1144 * Tests if the contact is a valid receiver for this actor
1146 * @param array $contact
1147 * @param array $tags
1149 * @return bool with receivers (user id)
1150 * @throws \Exception
1152 private static function isValidReceiverForActor(array $contact, array $tags): bool
1154 // Are we following the contact? Then this is a valid receiver
1155 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1159 // When the possible receiver isn't a community, then it is no valid receiver
1160 $owner = User::getOwnerDataById($contact['uid']);
1161 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1165 // Is the community account tagged?
1166 foreach ($tags as $tag) {
1167 if ($tag['type'] != 'Mention') {
1171 if (Strings::compareLink($tag['href'], $owner['url'])) {
1180 * Switches existing contacts to ActivityPub
1182 * @param integer $cid Contact ID
1183 * @param integer $uid User ID
1184 * @param string $url Profile URL
1186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1187 * @throws \ImagickException
1189 public static function switchContact(int $cid, int $uid, string $url)
1191 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1192 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1196 if (Contact::updateFromProbe($cid)) {
1197 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1200 // Send a new follow request to be sure that the connection still exists
1201 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1202 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1203 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1208 * @TODO Fix documentation and type-hints
1213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1214 * @throws \ImagickException
1216 private static function switchContacts($receivers, $actor)
1218 if (empty($actor)) {
1222 foreach ($receivers as $receiver) {
1223 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1224 if (DBA::isResult($contact)) {
1225 self::switchContact($contact['id'], $receiver['uid'], $actor);
1228 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1229 if (DBA::isResult($contact)) {
1230 self::switchContact($contact['id'], $receiver['uid'], $actor);
1236 * @TODO Fix documentation and type-hints
1238 * @param $object_data
1239 * @param array $activity
1243 private static function addActivityFields($object_data, array $activity)
1245 if (!empty($activity['published']) && empty($object_data['published'])) {
1246 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1249 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1250 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1253 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1254 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1256 if (!empty($object_data['object_id'])) {
1257 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1258 $objectId = Item::getURIByLink($object_data['object_id']);
1259 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1260 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1261 $object_data['object_id'] = $objectId;
1265 return $object_data;
1269 * Fetches the object data from external ressources if needed
1271 * @param string $object_id Object ID of the the provided object
1272 * @param array $object The provided object array
1273 * @param boolean $trust_source Do we trust the provided object?
1274 * @param integer $uid User ID for the signature that we use to fetch data
1276 * @return array|false with trusted and valid object data
1277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1278 * @throws \ImagickException
1280 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1282 // By fetching the type we check if the object is complete.
1283 $type = JsonLD::fetchElement($object, '@type');
1285 if (!$trust_source || empty($type)) {
1286 $data = Processor::fetchCachedActivity($object_id, $uid);
1287 if (!empty($data)) {
1288 $object = JsonLD::compact($data);
1289 Logger::info('Fetched content for ' . $object_id);
1291 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1293 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1294 if (!DBA::isResult($item)) {
1295 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1298 Logger::info('Using already stored item for url ' . $object_id);
1299 $data = ActivityPub\Transmitter::createNote($item);
1300 $object = JsonLD::compact($data);
1303 $id = JsonLD::fetchElement($object, '@id');
1305 Logger::info('Empty id');
1309 if ($id != $object_id) {
1310 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1314 Logger::info('Using original object for url ' . $object_id);
1317 $type = JsonLD::fetchElement($object, '@type');
1319 Logger::info('Empty type');
1323 // Lemmy is resharing "create" activities instead of content
1324 // We fetch the content from the activity.
1325 if (in_array($type, ['as:Create'])) {
1326 $object = $object['as:object'];
1327 $type = JsonLD::fetchElement($object, '@type');
1329 Logger::info('Empty type');
1332 $object_data = self::processObject($object);
1335 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1336 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1337 $object_data = self::processObject($object);
1339 if (!empty($data)) {
1340 $object_data['raw-object'] = json_encode($data);
1342 return $object_data;
1345 if ($type == 'as:Announce') {
1346 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1347 if (empty($object_id) || !is_string($object_id)) {
1350 return self::fetchObject($object_id, [], false, $uid);
1353 Logger::info('Unhandled object type: ' . $type);
1358 * Converts the language element (Used by Peertube)
1360 * @param array $languages
1361 * @return array Languages
1363 public static function processLanguages(array $languages): array
1365 if (empty($languages)) {
1369 $language_list = [];
1371 foreach ($languages as $language) {
1372 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1373 $language_list[$language['_:identifier']] = $language['as:name'];
1376 return $language_list;
1380 * Convert tags from JSON-LD format into a simplified format
1382 * @param array $tags Tags in JSON-LD format
1384 * @return array with tags in a simplified format
1386 public static function processTags(array $tags): array
1390 foreach ($tags as $tag) {
1395 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1396 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1397 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1399 if (empty($element['type'])) {
1403 if (empty($element['href'])) {
1404 $element['href'] = $element['name'];
1407 $taglist[] = $element;
1413 * Convert emojis from JSON-LD format into a simplified format
1415 * @param array $emojis
1416 * @return array with emojis in a simplified format
1418 private static function processEmojis(array $emojis): array
1422 foreach ($emojis as $emoji) {
1423 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1427 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1428 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1431 $emojilist[] = $element;
1438 * Convert attachments from JSON-LD format into a simplified format
1440 * @param array $attachments Attachments in JSON-LD format
1442 * @return array Attachments in a simplified format
1444 private static function processAttachments(array $attachments): array
1448 // Removes empty values
1449 $attachments = array_filter($attachments);
1451 foreach ($attachments as $attachment) {
1452 switch (JsonLD::fetchElement($attachment, '@type')) {
1457 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1458 foreach ($urls as $url) {
1459 // Single scalar URL case
1460 if (is_string($url)) {
1465 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1466 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1467 if (Strings::startsWith($mediaType, 'image')) {
1476 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1477 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1479 'image' => $pageImage,
1483 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1484 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1485 $imagePreviewUrl = null;
1487 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1488 $imageVariants = [];
1489 $previewVariants = [];
1490 foreach ($urls as $url) {
1491 // Scalar URL, no discrimination possible
1492 if (is_string($url)) {
1493 $imageFullUrl = $url;
1497 // Not sure what to do with a different Link media type than the base Image, we skip
1498 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1502 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1504 // Default URL choice if no discriminating width is provided
1505 $imageFullUrl = $href ?? $imageFullUrl;
1507 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1509 if ($href && $width) {
1510 $imageVariants[$width] = $href;
1511 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1512 $previewVariants[abs(632 - $width)] = $href;
1516 if ($imageVariants) {
1517 // Taking the maximum size image
1518 ksort($imageVariants);
1519 $imageFullUrl = array_pop($imageVariants);
1521 // Taking the minimum number distance to the target distance
1522 ksort($previewVariants);
1523 $imagePreviewUrl = array_shift($previewVariants);
1526 unset($imageVariants);
1527 unset($previewVariants);
1531 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1532 'mediaType' => $mediaType,
1533 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1534 'url' => $imageFullUrl,
1535 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1540 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1541 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1542 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1543 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1544 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1545 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1546 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1555 * Convert questions from JSON-LD format into a simplified format
1557 * @param array $object
1559 * @return array Questions in a simplified format
1561 private static function processQuestion(array $object): array
1565 if (!empty($object['as:oneOf'])) {
1566 $question['multiple'] = false;
1567 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1568 } elseif (!empty($object['as:anyOf'])) {
1569 $question['multiple'] = true;
1570 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1575 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1576 if (!empty($closed)) {
1577 $question['end-time'] = $closed;
1579 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1582 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1583 $question['options'] = [];
1587 foreach ($options as $option) {
1588 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1592 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1594 if (empty($option['as:replies'])) {
1598 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1600 $question['options'][] = ['name' => $name, 'replies' => $replies];
1602 $voters += (int)$replies;
1605 // For single choice question we can count the number of voters if not provided (like with Misskey)
1606 if (empty($question['voters']) && !$question['multiple']) {
1607 $question['voters'] = $voters;
1614 * Fetch the original source or content with the "language" Markdown or HTML
1616 * @param array $object
1617 * @param array $object_data
1619 * @return array Object data (?)
1620 * @throws \Exception
1622 private static function getSource(array $object, array $object_data): array
1624 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1625 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1626 if (!empty($object_data['source'])) {
1627 return $object_data;
1630 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1631 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1632 if (!empty($object_data['source'])) {
1633 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1634 return $object_data;
1637 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1638 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1639 if (!empty($object_data['source'])) {
1640 $object_data['source'] = HTML::toBBCode($object_data['source']);
1641 return $object_data;
1644 return $object_data;
1648 * Extracts a potential alternate URL from a list of additional URL elements
1650 * @param array $urls
1653 private static function extractAlternateUrl(array $urls): string
1656 foreach ($urls as $key => $url) {
1657 // Not a list but a single URL element
1658 if (!is_numeric($key)) {
1662 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1666 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1671 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1672 if (empty($mediatype)) {
1676 if ($mediatype == 'text/html') {
1677 $alternateUrl = $href;
1681 return $alternateUrl;
1685 * Check if the "as:url" element is an array with multiple links
1686 * This is the case with audio and video posts.
1687 * Then the links are added as attachments
1689 * @param array $urls The object URL list
1690 * @return array an array of attachments
1692 private static function processAttachmentUrls(array $urls): array
1695 foreach ($urls as $key => $url) {
1696 // Not a list but a single URL element
1697 if (!is_numeric($key)) {
1701 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1705 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1710 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1711 if (empty($mediatype)) {
1715 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1717 if ($filetype == 'audio') {
1718 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1719 } elseif ($filetype == 'video') {
1720 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1721 // PeerTube audio-only track
1722 if ($height === 0) {
1726 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1727 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1728 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1729 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1731 // For Torrent links we always store the highest resolution
1732 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1736 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1737 } elseif ($mediatype == 'application/x-mpegURL') {
1738 // PeerTube exception, actual video link is in the tags of this URL element
1739 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1743 return array_values($attachments);
1747 * Fetches data from the object part of an activity
1749 * @param array $object
1751 * @return array|bool Object data or FALSE if $object does not contain @id element
1752 * @throws \Exception
1754 private static function processObject(array $object)
1756 if (!JsonLD::fetchElement($object, '@id')) {
1761 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1762 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1763 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1765 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1766 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1767 $object_data['reply-to-id'] = $object_data['id'];
1769 // On activities the "reply to" is the id of the object it refers to
1770 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1771 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1772 if (!empty($object_id)) {
1773 $object_data['reply-to-id'] = $object_id;
1777 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1778 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1779 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1780 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1781 $object_data['reply-to-id'] = $replyToId;
1785 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1786 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1788 if (empty($object_data['updated'])) {
1789 $object_data['updated'] = $object_data['published'];
1792 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1793 $object_data['published'] = $object_data['updated'];
1796 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1797 if (empty($actor)) {
1798 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1801 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1802 $location = JsonLD::fetchElement($location, 'location', '@value');
1804 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1805 // down to HTML and then finally format to plaintext.
1806 $location = Markdown::convert($location);
1807 $location = BBCode::toPlaintext($location);
1810 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1811 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1812 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1813 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1814 $object_data['actor'] = $object_data['author'] = $actor;
1815 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1816 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1817 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1818 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1819 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1820 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1821 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1822 $object_data = self::getSource($object, $object_data);
1823 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1824 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1825 $object_data['location'] = $location;
1826 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1827 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1828 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1829 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1830 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1831 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1832 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1833 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1834 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1835 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1836 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1838 // Special treatment for Hubzilla links
1839 if (is_array($object_data['alternate-url'])) {
1840 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1842 if (!is_string($object_data['alternate-url'])) {
1843 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1847 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1848 $object_data['alternate-url'] = null;
1851 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1852 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1853 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1856 // For page types we expect that the alternate url posts to some page.
1857 // So we add this to the attachments if it differs from the id.
1858 // Currently only Lemmy is using the page type.
1859 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1860 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1861 $object_data['alternate-url'] = null;
1864 if ($object_data['object_type'] == 'as:Question') {
1865 $object_data['question'] = self::processQuestion($object);
1868 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1869 $receivers = $reception_types = [];
1870 foreach ($receiverdata as $key => $data) {
1871 $receivers[$key] = $data['uid'];
1872 $reception_types[$data['uid']] = $data['type'] ?? 0;
1875 $object_data['receiver_urls'] = self::getReceiverURL($object);
1876 $object_data['receiver'] = $receivers;
1877 $object_data['reception_type'] = $reception_types;
1879 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1880 unset($object_data['receiver'][-1]);
1881 unset($object_data['reception_type'][-1]);
1883 return $object_data;