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\Database\Database;
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['type'] == 'Application' && $apcontact['nick'] == 'relay') {
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 $fetchQueue = new FetchQueue();
159 self::processActivity($fetchQueue, $ldactivity, $body, $uid, $trust_source, true, $signer, $http_signer);
160 $fetchQueue->process();
163 private static function enqueuePost(array $ldactivity = [], string $type, int $uid, string $http_signer): array
166 'activity-id' => $ldactivity['id'],
167 'object-id' => $ldactivity['object_id'],
169 'object-type' => $ldactivity['object_type'],
170 'activity' => json_encode($ldactivity, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
171 'received' => DateTimeFormat::utcNow(),
174 if (!empty($ldactivity['object_object_type'])) {
175 $fields['object-object-type'] = $ldactivity['object_object_type'];
178 if (!empty($http_signer)) {
179 $fields['signer'] = $http_signer;
182 DBA::insert('inbox-entry', $fields, Database::INSERT_IGNORE);
184 $queue = DBA::selectFirst('inbox-entry', ['id'], ['activity-id' => $ldactivity['id']]);
185 if (!empty($queue['id'])) {
186 $ldactivity['entry-id'] = $queue['id'];
187 DBA::insert('inbox-entry-receiver', ['queue-id' => $queue['id'], 'uid' => $uid], Database::INSERT_IGNORE);
192 public static function removeFromQueue(array $activity = [])
194 if (empty($activity['entry-id'])) {
197 DBA::delete('inbox-entry', ['id' => $activity['entry-id']]);
201 * Process incoming posts from relays
203 * @param array $activity
204 * @param string $actor
207 private static function processRelayPost(array $activity, string $actor)
209 $type = JsonLD::fetchElement($activity, '@type');
211 Logger::info('Empty type', ['activity' => $activity]);
215 if ($type != 'as:Announce') {
216 Logger::info('Not an announcement', ['activity' => $activity]);
220 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
221 if (empty($object_id)) {
222 Logger::info('No object id found', ['activity' => $activity]);
226 $contact = Contact::getByURL($actor);
227 if (empty($contact)) {
228 Logger::info('Relay contact not found', ['actor' => $actor]);
232 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
233 Logger::notice('Relay is no sharer', ['actor' => $actor]);
237 Logger::info('Got relayed message id', ['id' => $object_id]);
239 $item_id = Item::searchByLink($object_id);
241 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
245 $fetchQueue = new FetchQueue();
247 $id = Processor::fetchMissingActivity($fetchQueue, $object_id, [], $actor, self::COMPLETION_RELAY);
249 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
253 $fetchQueue->process();
255 $item_id = Item::searchByLink($object_id);
257 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
259 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
264 * Fetches the object type for a given object id
266 * @param array $activity
267 * @param string $object_id Object ID of the the provided object
268 * @param integer $uid User ID
270 * @return string with object type or NULL
271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 * @throws \ImagickException
274 private static function fetchObjectType(array $activity, string $object_id, int $uid = 0)
276 if (!empty($activity['as:object'])) {
277 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
278 if (!empty($object_type)) {
283 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
284 // We just assume "note" since it doesn't make a difference for the further processing
288 $profile = APContact::getByURL($object_id);
289 if (!empty($profile['type'])) {
290 APContact::unmarkForArchival($profile);
291 return 'as:' . $profile['type'];
294 $data = ActivityPub::fetchContent($object_id, $uid);
296 $object = JsonLD::compact($data);
297 $type = JsonLD::fetchElement($object, '@type');
307 * Prepare the object array
309 * @param array $activity Array with activity data
310 * @param integer $uid User ID
311 * @param boolean $push Message had been pushed to our system
312 * @param boolean $trust_source Do we trust the source?
314 * @return array with object data
315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
316 * @throws \ImagickException
318 public static function prepareObjectData(array $activity, int $uid, bool $push, bool &$trust_source): array
320 $id = JsonLD::fetchElement($activity, '@id');
321 if (!empty($id) && !$trust_source) {
322 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
324 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
325 if (!empty($fetched_activity)) {
326 $object = JsonLD::compact($fetched_activity);
327 $fetched_id = JsonLD::fetchElement($object, '@id');
328 if ($fetched_id == $id) {
329 Logger::info('Activity had been fetched successfully', ['id' => $id]);
330 $trust_source = true;
333 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
336 Logger::info('Activity could not been fetched', ['id' => $id]);
340 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
342 Logger::info('Empty actor', ['activity' => $activity]);
346 $type = JsonLD::fetchElement($activity, '@type');
348 // Fetch all receivers from to, cc, bto and bcc
349 $receiverdata = self::getReceivers($activity, $actor);
350 $receivers = $reception_types = [];
351 foreach ($receiverdata as $key => $data) {
352 $receivers[$key] = $data['uid'];
353 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
356 $urls = self::getReceiverURL($activity);
358 // When it is a delivery to a personal inbox we add that user to the receivers
360 $additional = [$uid => $uid];
361 $receivers = array_replace($receivers, $additional);
362 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]))) {
363 $reception_types[$uid] = self::TARGET_BCC;
364 $owner = User::getOwnerDataById($uid);
365 if (!empty($owner['url'])) {
366 $urls['as:bcc'][] = $owner['url'];
371 // We possibly need some user to fetch private content,
372 // so we fetch one out of the receivers if no uid is provided.
373 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
375 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
376 if (empty($object_id)) {
377 Logger::info('No object found');
381 if (!is_string($object_id)) {
382 Logger::info('Invalid object id', ['object' => $object_id]);
386 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
388 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
389 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
390 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
392 $type = $object_type;
393 $activity = JsonLD::compact($data);
395 // Some variables need to be refetched since the activity changed
396 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
397 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
398 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
402 // Any activities on account types must not be altered
403 if (in_array($object_type, self::ACCOUNT_TYPES)) {
405 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
406 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
407 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
408 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
409 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
410 $object_data['push'] = $push;
411 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
412 // Fetch the content only on activities where this matters
413 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
414 // Always fetch on "Announce"
415 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
416 if (empty($object_data)) {
417 Logger::info("Object data couldn't be processed");
421 $object_data['object_id'] = $object_id;
423 if ($type == 'as:Announce') {
424 $object_data['push'] = false;
426 $object_data['push'] = $push;
429 // Test if it is an answer to a mail
430 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
431 $object_data['directmessage'] = true;
433 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
435 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
436 // Create a mostly empty array out of the activity data (instead of the object).
437 // This way we later don't have to check for the existence of each individual array element.
438 $object_data = self::processObject($activity);
439 $object_data['name'] = $type;
440 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
441 $object_data['object_id'] = $object_id;
442 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
443 $object_data['push'] = $push;
444 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
446 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
447 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
448 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
449 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
450 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
451 $object_data['push'] = $push;
454 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
455 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
456 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
457 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
458 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
459 $object_data['push'] = $push;
461 // An Undo is done on the object of an object, so we need that type as well
462 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
463 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
467 $object_data = self::addActivityFields($object_data, $activity);
469 if (empty($object_data['object_type'])) {
470 $object_data['object_type'] = $object_type;
473 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
474 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
475 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
479 $object_data['type'] = $type;
480 $object_data['actor'] = $actor;
481 $object_data['item_receiver'] = $receivers;
482 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
483 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
485 $author = $object_data['author'] ?? $actor;
486 if (!empty($author) && !empty($object_data['id'])) {
487 $author_host = parse_url($author, PHP_URL_HOST);
488 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
489 if ($author_host == $id_host) {
490 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
492 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
493 $trust_source = false;
497 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
503 * Fetches the first user id from the receiver array
505 * @param array $receivers Array with receivers
506 * @return integer user id;
508 public static function getFirstUserFromReceivers(array $receivers): int
510 foreach ($receivers as $receiver) {
511 if (!empty($receiver)) {
519 * Processes the activity object
521 * @param FetchQueue $fetchQueue
522 * @param array $activity Array with activity data
523 * @param string $body The unprocessed body
524 * @param int|null $uid User ID
525 * @param boolean $trust_source Do we trust the source?
526 * @param boolean $push Message had been pushed to our system
527 * @param array $signer The signer of the post
528 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
529 * @throws \ImagickException
531 public static function processActivity(FetchQueue $fetchQueue, array $activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [], string $http_signer = '')
533 $type = JsonLD::fetchElement($activity, '@type');
535 Logger::info('Empty type', ['activity' => $activity]);
539 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
540 Logger::info('Empty object', ['activity' => $activity]);
544 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
546 Logger::info('Empty actor', ['activity' => $activity]);
550 if (is_array($activity['as:object'])) {
551 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
556 // Test the provided signatures against the actor and "attributedTo"
558 if (!empty($attributed_to) && !empty($actor)) {
559 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
561 $trust_source = in_array($actor, $signer);
565 // $trust_source is called by reference and is set to true if the content was retrieved successfully
566 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
567 if (empty($object_data)) {
568 Logger::info('No object data found', ['activity' => $activity]);
572 // Lemmy is announcing activities.
573 // We are changing the announces into regular activities.
574 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
575 $type = $object_data['type'];
578 if (!$trust_source) {
579 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
583 if (!empty($body) && empty($object_data['raw'])) {
584 $object_data['raw'] = $body;
587 // Internal flag for thread completion. See Processor.php
588 if (!empty($activity['thread-completion'])) {
589 $object_data['thread-completion'] = $activity['thread-completion'];
592 if (!empty($activity['completion-mode'])) {
593 $object_data['completion-mode'] = $activity['completion-mode'];
596 if (!empty($activity['thread-children-type'])) {
597 $object_data['thread-children-type'] = $activity['thread-children-type'];
600 // Internal flag for posts that arrived via relay
601 if (!empty($activity['from-relay'])) {
602 $object_data['from-relay'] = $activity['from-relay'];
605 $object_data = self::enqueuePost($object_data, $type, $uid, $http_signer);
607 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
608 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
613 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
614 $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
615 ActivityPub\Processor::postItem($object_data, $item);
616 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
617 // Unhandled Peertube activity
619 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
624 if (in_array($object_data['object_type'], ['as:Event'])) {
625 $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
626 ActivityPub\Processor::postItem($object_data, $item);
628 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
633 if ($object_data['object_type'] == 'as:tag') {
634 ActivityPub\Processor::addTag($object_data);
635 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
636 ActivityPub\Processor::addToFeaturedCollection($object_data);
637 } elseif ($object_data['object_type'] == '') {
638 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
640 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
645 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
646 $object_data['thread-completion'] = Contact::getIdForURL($actor);
647 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
649 $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
654 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
655 ActivityPub\Processor::postItem($object_data, $item);
657 $announce_object_data = self::processObject($activity);
658 $announce_object_data['name'] = $type;
659 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
660 $announce_object_data['object_id'] = $object_data['object_id'];
661 $announce_object_data['object_type'] = $object_data['object_type'];
662 $announce_object_data['push'] = $push;
665 $announce_object_data['raw'] = $body;
668 ActivityPub\Processor::createActivity($fetchQueue, $announce_object_data, Activity::ANNOUNCE);
670 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
675 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
676 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::LIKE);
677 } elseif ($object_data['object_type'] == '') {
678 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
680 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
685 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
686 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::DISLIKE);
687 } elseif ($object_data['object_type'] == '') {
688 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
690 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
694 case 'as:TentativeAccept':
695 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
696 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTENDMAYBE);
698 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
703 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
704 ActivityPub\Processor::updateItem($fetchQueue, $object_data);
705 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
706 ActivityPub\Processor::updatePerson($object_data);
707 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
708 // Unhandled Peertube activity
710 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
715 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
716 ActivityPub\Processor::deleteItem($object_data);
717 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
718 ActivityPub\Processor::deletePerson($object_data);
719 } elseif ($object_data['object_type'] == '') {
720 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
722 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
727 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
728 ActivityPub\Processor::blockAccount($object_data);
730 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
735 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
736 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
737 } elseif ($object_data['object_type'] == '') {
738 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
740 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
745 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
746 ActivityPub\Processor::followUser($object_data);
747 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
748 $object_data['reply-to-id'] = $object_data['object_id'];
749 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::FOLLOW);
751 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
756 if ($object_data['object_type'] == 'as:Follow') {
757 ActivityPub\Processor::acceptFollowUser($object_data);
758 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
759 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTEND);
761 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
766 if ($object_data['object_type'] == 'as:Follow') {
767 ActivityPub\Processor::rejectFollowUser($object_data);
768 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
769 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTENDNO);
771 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
776 if (($object_data['object_type'] == 'as:Follow') &&
777 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
778 ActivityPub\Processor::undoFollowUser($object_data);
779 } elseif (($object_data['object_type'] == 'as:Follow') &&
780 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
781 ActivityPub\Processor::undoActivity($object_data);
782 } elseif (($object_data['object_type'] == 'as:Accept') &&
783 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
784 ActivityPub\Processor::rejectFollowUser($object_data);
785 } elseif (($object_data['object_type'] == 'as:Block') &&
786 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
787 ActivityPub\Processor::unblockAccount($object_data);
788 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
789 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
790 ActivityPub\Processor::undoActivity($object_data);
791 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
792 empty($object_data['object_object_type'])) {
793 // We cannot detect the target object. So we can ignore it.
794 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
795 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
796 // Unhandled Peertube activity
798 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
803 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
804 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::VIEW);
805 } elseif ($object_data['object_type'] == '') {
806 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
808 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
812 case 'litepub:EmojiReact':
813 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
814 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::EMOJIREACT);
815 } elseif ($object_data['object_type'] == '') {
816 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
818 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
823 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
824 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
830 * Stores unhandled or unknown Activities as a file
832 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
833 * @param string $type Activity type
834 * @param array $object_data Preprocessed array that is generated out of the received activity
835 * @param array $activity Array with activity data
836 * @param string $body The unprocessed body
837 * @param integer $uid User ID
838 * @param boolean $trust_source Do we trust the source?
839 * @param boolean $push Message had been pushed to our system
840 * @param array $signer The signer of the post
843 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 = [])
845 if (!DI::config()->get('debug', 'ap_log_unknown')) {
849 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
851 if (!empty($object_data['object_type'])) {
852 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
855 if (!empty($object_data['object_object_type'])) {
856 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
859 $tempfile = tempnam(System::getTempPath(), $file);
860 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));
861 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
865 * Fetch a user id from an activity array
867 * @param array $activity
868 * @param string $actor
870 * @return int user id
872 public static function getBestUserForActivity(array $activity): int
875 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
877 $receivers = self::getReceivers($activity, $actor);
878 foreach ($receivers as $receiver) {
879 if ($receiver['type'] == self::TARGET_GLOBAL) {
882 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
883 $uid = $receiver['uid'];
887 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
889 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
890 if (!empty($contact['uid'])) {
891 $uid = $contact['uid'];
898 // @TODO Missing documentation
899 public static function getReceiverURL(array $activity): array
903 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
904 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
905 if (empty($receiver_list)) {
909 foreach ($receiver_list as $receiver) {
910 if ($receiver == self::PUBLIC_COLLECTION) {
911 $receiver = ActivityPub::PUBLIC_COLLECTION;
913 $urls[$element][] = $receiver;
921 * Fetch the receiver list from an activity array
923 * @param array $activity
924 * @param string $actor
926 * @param boolean $fetch_unlisted
928 * @return array with receivers (user id)
931 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
933 $reply = $receivers = $profile = [];
935 // When it is an answer, we inherite the receivers from the parent
936 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
937 if (!empty($replyto)) {
940 // Fix possibly wrong item URI (could be an answer to a plink uri)
941 $fixedReplyTo = Item::getURIByLink($replyto);
942 if (!empty($fixedReplyTo)) {
943 $reply[] = $fixedReplyTo;
947 // Fetch all posts that refer to the object id
948 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
949 if (!empty($object_id)) {
950 $reply[] = $object_id;
953 if (!empty($reply)) {
954 $parents = Post::select(['uid'], ['uri' => $reply]);
955 while ($parent = Post::fetch($parents)) {
956 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
958 DBA::close($parents);
961 if (!empty($actor)) {
962 $profile = APContact::getByURL($actor);
963 $followers = $profile['followers'] ?? '';
964 $is_forum = ($actor['type'] ?? '') == 'Group';
965 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
967 Logger::info('Empty actor', ['activity' => $activity]);
972 // We have to prevent false follower assumptions upon thread completions
973 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
975 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
976 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
977 if (empty($receiver_list)) {
981 foreach ($receiver_list as $receiver) {
982 if ($receiver == self::PUBLIC_COLLECTION) {
983 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
986 // Add receiver "-1" for unlisted posts
987 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
988 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
991 // Fetch the receivers for the public and the followers collection
992 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
993 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
997 // Fetching all directly addressed receivers
998 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
999 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1000 if (!DBA::isResult($contact)) {
1004 // Check if the potential receiver is following the actor
1005 // Exception: The receiver is targetted via "to" or this is a comment
1006 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1007 $networks = Protocol::FEDERATED;
1008 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1009 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1011 // Forum posts are only accepted from forum contacts
1012 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1013 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1016 if (!DBA::exists('contact', $condition)) {
1021 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1022 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1025 $type = self::TARGET_TO;
1028 $type = self::TARGET_CC;
1031 $type = self::TARGET_BTO;
1034 $type = self::TARGET_BCC;
1038 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1043 self::switchContacts($receivers, $actor);
1049 * Fetch the receiver list of a given actor
1051 * @param string $actor
1052 * @param array $tags
1053 * @param array $receivers
1054 * @param integer $target_type
1055 * @param array $profile
1057 * @return array with receivers (user id)
1058 * @throws \Exception
1060 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1062 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1063 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1065 if (!empty($profile['uri-id'])) {
1066 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1067 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1068 while ($contact = DBA::fetch($contacts)) {
1069 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1070 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1073 DBA::close($contacts);
1075 // This part will only be called while post update 1426 wasn't finished
1076 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1077 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1078 while ($contact = DBA::fetch($contacts)) {
1079 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1080 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1083 DBA::close($contacts);
1085 // The queries are split because of performance issues
1086 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1087 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1088 while ($contact = DBA::fetch($contacts)) {
1089 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1090 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1093 DBA::close($contacts);
1099 * Tests if the contact is a valid receiver for this actor
1101 * @param array $contact
1102 * @param array $tags
1104 * @return bool with receivers (user id)
1105 * @throws \Exception
1107 private static function isValidReceiverForActor(array $contact, array $tags): bool
1109 // Are we following the contact? Then this is a valid receiver
1110 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1114 // When the possible receiver isn't a community, then it is no valid receiver
1115 $owner = User::getOwnerDataById($contact['uid']);
1116 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1120 // Is the community account tagged?
1121 foreach ($tags as $tag) {
1122 if ($tag['type'] != 'Mention') {
1126 if (Strings::compareLink($tag['href'], $owner['url'])) {
1135 * Switches existing contacts to ActivityPub
1137 * @param integer $cid Contact ID
1138 * @param integer $uid User ID
1139 * @param string $url Profile URL
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1142 * @throws \ImagickException
1144 public static function switchContact(int $cid, int $uid, string $url)
1146 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1147 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1151 if (Contact::updateFromProbe($cid)) {
1152 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1155 // Send a new follow request to be sure that the connection still exists
1156 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1157 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1158 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1163 * @TODO Fix documentation and type-hints
1168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1169 * @throws \ImagickException
1171 private static function switchContacts($receivers, $actor)
1173 if (empty($actor)) {
1177 foreach ($receivers as $receiver) {
1178 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1179 if (DBA::isResult($contact)) {
1180 self::switchContact($contact['id'], $receiver['uid'], $actor);
1183 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1184 if (DBA::isResult($contact)) {
1185 self::switchContact($contact['id'], $receiver['uid'], $actor);
1191 * @TODO Fix documentation and type-hints
1193 * @param $object_data
1194 * @param array $activity
1198 private static function addActivityFields($object_data, array $activity)
1200 if (!empty($activity['published']) && empty($object_data['published'])) {
1201 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1204 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1205 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1208 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1209 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1211 if (!empty($object_data['object_id'])) {
1212 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1213 $objectId = Item::getURIByLink($object_data['object_id']);
1214 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1215 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1216 $object_data['object_id'] = $objectId;
1220 return $object_data;
1224 * Fetches the object data from external ressources if needed
1226 * @param string $object_id Object ID of the the provided object
1227 * @param array $object The provided object array
1228 * @param boolean $trust_source Do we trust the provided object?
1229 * @param integer $uid User ID for the signature that we use to fetch data
1231 * @return array|false with trusted and valid object data
1232 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1233 * @throws \ImagickException
1235 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1237 // By fetching the type we check if the object is complete.
1238 $type = JsonLD::fetchElement($object, '@type');
1240 if (!$trust_source || empty($type)) {
1241 $data = ActivityPub::fetchContent($object_id, $uid);
1242 if (!empty($data)) {
1243 $object = JsonLD::compact($data);
1244 Logger::info('Fetched content for ' . $object_id);
1246 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1248 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1249 if (!DBA::isResult($item)) {
1250 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1253 Logger::info('Using already stored item for url ' . $object_id);
1254 $data = ActivityPub\Transmitter::createNote($item);
1255 $object = JsonLD::compact($data);
1258 $id = JsonLD::fetchElement($object, '@id');
1260 Logger::info('Empty id');
1264 if ($id != $object_id) {
1265 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1269 Logger::info('Using original object for url ' . $object_id);
1272 $type = JsonLD::fetchElement($object, '@type');
1274 Logger::info('Empty type');
1278 // Lemmy is resharing "create" activities instead of content
1279 // We fetch the content from the activity.
1280 if (in_array($type, ['as:Create'])) {
1281 $object = $object['as:object'];
1282 $type = JsonLD::fetchElement($object, '@type');
1284 Logger::info('Empty type');
1287 $object_data = self::processObject($object);
1290 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1291 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1292 $object_data = self::processObject($object);
1294 if (!empty($data)) {
1295 $object_data['raw'] = json_encode($data);
1297 return $object_data;
1300 if ($type == 'as:Announce') {
1301 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1302 if (empty($object_id) || !is_string($object_id)) {
1305 return self::fetchObject($object_id, [], false, $uid);
1308 Logger::info('Unhandled object type: ' . $type);
1313 * Converts the language element (Used by Peertube)
1315 * @param array $languages
1316 * @return array Languages
1318 public static function processLanguages(array $languages): array
1320 if (empty($languages)) {
1324 $language_list = [];
1326 foreach ($languages as $language) {
1327 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1328 $language_list[$language['_:identifier']] = $language['as:name'];
1331 return $language_list;
1335 * Convert tags from JSON-LD format into a simplified format
1337 * @param array $tags Tags in JSON-LD format
1339 * @return array with tags in a simplified format
1341 public static function processTags(array $tags): array
1345 foreach ($tags as $tag) {
1350 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1351 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1352 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1354 if (empty($element['type'])) {
1358 if (empty($element['href'])) {
1359 $element['href'] = $element['name'];
1362 $taglist[] = $element;
1368 * Convert emojis from JSON-LD format into a simplified format
1370 * @param array $emojis
1371 * @return array with emojis in a simplified format
1373 private static function processEmojis(array $emojis): array
1377 foreach ($emojis as $emoji) {
1378 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1382 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1383 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1386 $emojilist[] = $element;
1393 * Convert attachments from JSON-LD format into a simplified format
1395 * @param array $attachments Attachments in JSON-LD format
1397 * @return array Attachments in a simplified format
1399 private static function processAttachments(array $attachments): array
1403 // Removes empty values
1404 $attachments = array_filter($attachments);
1406 foreach ($attachments as $attachment) {
1407 switch (JsonLD::fetchElement($attachment, '@type')) {
1412 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1413 foreach ($urls as $url) {
1414 // Single scalar URL case
1415 if (is_string($url)) {
1420 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1421 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1422 if (Strings::startsWith($mediaType, 'image')) {
1431 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1432 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1434 'image' => $pageImage,
1438 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1439 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1440 $imagePreviewUrl = null;
1442 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1443 $imageVariants = [];
1444 $previewVariants = [];
1445 foreach ($urls as $url) {
1446 // Scalar URL, no discrimination possible
1447 if (is_string($url)) {
1448 $imageFullUrl = $url;
1452 // Not sure what to do with a different Link media type than the base Image, we skip
1453 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1457 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1459 // Default URL choice if no discriminating width is provided
1460 $imageFullUrl = $href ?? $imageFullUrl;
1462 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1464 if ($href && $width) {
1465 $imageVariants[$width] = $href;
1466 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1467 $previewVariants[abs(632 - $width)] = $href;
1471 if ($imageVariants) {
1472 // Taking the maximum size image
1473 ksort($imageVariants);
1474 $imageFullUrl = array_pop($imageVariants);
1476 // Taking the minimum number distance to the target distance
1477 ksort($previewVariants);
1478 $imagePreviewUrl = array_shift($previewVariants);
1481 unset($imageVariants);
1482 unset($previewVariants);
1486 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1487 'mediaType' => $mediaType,
1488 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1489 'url' => $imageFullUrl,
1490 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1495 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1496 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1497 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1498 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1499 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1500 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1501 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1510 * Convert questions from JSON-LD format into a simplified format
1512 * @param array $object
1514 * @return array Questions in a simplified format
1516 private static function processQuestion(array $object): array
1520 if (!empty($object['as:oneOf'])) {
1521 $question['multiple'] = false;
1522 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1523 } elseif (!empty($object['as:anyOf'])) {
1524 $question['multiple'] = true;
1525 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1530 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1531 if (!empty($closed)) {
1532 $question['end-time'] = $closed;
1534 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1537 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1538 $question['options'] = [];
1542 foreach ($options as $option) {
1543 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1547 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1549 if (empty($option['as:replies'])) {
1553 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1555 $question['options'][] = ['name' => $name, 'replies' => $replies];
1557 $voters += (int)$replies;
1560 // For single choice question we can count the number of voters if not provided (like with Misskey)
1561 if (empty($question['voters']) && !$question['multiple']) {
1562 $question['voters'] = $voters;
1569 * Fetch the original source or content with the "language" Markdown or HTML
1571 * @param array $object
1572 * @param array $object_data
1574 * @return array Object data (?)
1575 * @throws \Exception
1577 private static function getSource(array $object, array $object_data): array
1579 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1580 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1581 if (!empty($object_data['source'])) {
1582 return $object_data;
1585 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1586 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1587 if (!empty($object_data['source'])) {
1588 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1589 return $object_data;
1592 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1593 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1594 if (!empty($object_data['source'])) {
1595 $object_data['source'] = HTML::toBBCode($object_data['source']);
1596 return $object_data;
1599 return $object_data;
1603 * Extracts a potential alternate URL from a list of additional URL elements
1605 * @param array $urls
1608 private static function extractAlternateUrl(array $urls): string
1611 foreach ($urls as $key => $url) {
1612 // Not a list but a single URL element
1613 if (!is_numeric($key)) {
1617 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1621 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1626 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1627 if (empty($mediatype)) {
1631 if ($mediatype == 'text/html') {
1632 $alternateUrl = $href;
1636 return $alternateUrl;
1640 * Check if the "as:url" element is an array with multiple links
1641 * This is the case with audio and video posts.
1642 * Then the links are added as attachments
1644 * @param array $urls The object URL list
1645 * @return array an array of attachments
1647 private static function processAttachmentUrls(array $urls): array
1650 foreach ($urls as $key => $url) {
1651 // Not a list but a single URL element
1652 if (!is_numeric($key)) {
1656 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1660 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1665 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1666 if (empty($mediatype)) {
1670 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1672 if ($filetype == 'audio') {
1673 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1674 } elseif ($filetype == 'video') {
1675 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1676 // PeerTube audio-only track
1677 if ($height === 0) {
1681 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1682 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1683 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1684 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1686 // For Torrent links we always store the highest resolution
1687 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1691 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1692 } elseif ($mediatype == 'application/x-mpegURL') {
1693 // PeerTube exception, actual video link is in the tags of this URL element
1694 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1698 return array_values($attachments);
1702 * Fetches data from the object part of an activity
1704 * @param array $object
1706 * @return array|bool Object data or FALSE if $object does not contain @id element
1707 * @throws \Exception
1709 private static function processObject(array $object)
1711 if (!JsonLD::fetchElement($object, '@id')) {
1716 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1717 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1718 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1720 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1721 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1722 $object_data['reply-to-id'] = $object_data['id'];
1724 // On activities the "reply to" is the id of the object it refers to
1725 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1726 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1727 if (!empty($object_id)) {
1728 $object_data['reply-to-id'] = $object_id;
1732 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1733 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1734 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1735 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1736 $object_data['reply-to-id'] = $replyToId;
1740 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1741 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1743 if (empty($object_data['updated'])) {
1744 $object_data['updated'] = $object_data['published'];
1747 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1748 $object_data['published'] = $object_data['updated'];
1751 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1752 if (empty($actor)) {
1753 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1756 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1757 $location = JsonLD::fetchElement($location, 'location', '@value');
1759 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1760 // down to HTML and then finally format to plaintext.
1761 $location = Markdown::convert($location);
1762 $location = BBCode::toPlaintext($location);
1765 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1766 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1767 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1768 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1769 $object_data['actor'] = $object_data['author'] = $actor;
1770 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1771 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1772 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1773 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1774 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1775 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1776 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1777 $object_data = self::getSource($object, $object_data);
1778 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1779 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1780 $object_data['location'] = $location;
1781 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1782 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1783 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1784 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1785 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1786 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1787 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1788 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1789 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1790 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1791 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1793 // Special treatment for Hubzilla links
1794 if (is_array($object_data['alternate-url'])) {
1795 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1797 if (!is_string($object_data['alternate-url'])) {
1798 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1802 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1803 $object_data['alternate-url'] = null;
1806 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1807 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1808 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1811 // For page types we expect that the alternate url posts to some page.
1812 // So we add this to the attachments if it differs from the id.
1813 // Currently only Lemmy is using the page type.
1814 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1815 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1816 $object_data['alternate-url'] = null;
1819 if ($object_data['object_type'] == 'as:Question') {
1820 $object_data['question'] = self::processQuestion($object);
1823 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1824 $receivers = $reception_types = [];
1825 foreach ($receiverdata as $key => $data) {
1826 $receivers[$key] = $data['uid'];
1827 $reception_types[$data['uid']] = $data['type'] ?? 0;
1830 $object_data['receiver_urls'] = self::getReceiverURL($object);
1831 $object_data['receiver'] = $receivers;
1832 $object_data['reception_type'] = $reception_types;
1834 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1835 unset($object_data['receiver'][-1]);
1836 unset($object_data['reception_type'][-1]);
1838 // Common object data:
1841 // @context, type, actor, signature, mediaType, duration, replies, icon
1843 // Also missing: (Defined in the standard, but currently unused)
1844 // audience, preview, endTime, startTime, image
1849 // contentMap, announcement_count, announcements, context_id, likes, like_count
1850 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1855 // category, licence, language, commentsEnabled
1858 // views, waitTranscoding, state, support, subtitleLanguage
1859 // likes, dislikes, shares, comments
1861 return $object_data;