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::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 $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, 'actor' => $actor]);
215 if ($type != 'as:Announce') {
216 Logger::info('Not an announcement', ['activity' => $activity, 'actor' => $actor]);
220 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
221 if (empty($object_id)) {
222 Logger::info('No object id found', ['activity' => $activity, 'actor' => $actor]);
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, 'actor' => $actor]);
239 $item_id = Item::searchByLink($object_id);
241 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id, 'actor' => $actor]);
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, 'actor' => $actor]);
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, 'actor' => $actor]);
259 Logger::notice('Relayed message had not been stored', ['id' => $object_id, 'actor' => $actor]);
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
618 self::removeFromQueue($object_data);
620 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
625 if (in_array($object_data['object_type'], ['as:Event'])) {
626 $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
627 ActivityPub\Processor::postItem($object_data, $item);
629 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
634 if ($object_data['object_type'] == 'as:tag') {
635 ActivityPub\Processor::addTag($object_data);
636 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
637 ActivityPub\Processor::addToFeaturedCollection($object_data);
638 } elseif ($object_data['object_type'] == '') {
639 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
641 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
646 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
647 $object_data['thread-completion'] = Contact::getIdForURL($actor);
648 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
650 $item = ActivityPub\Processor::createItem($fetchQueue, $object_data);
655 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
656 ActivityPub\Processor::postItem($object_data, $item);
658 $announce_object_data = self::processObject($activity);
659 $announce_object_data['name'] = $type;
660 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
661 $announce_object_data['object_id'] = $object_data['object_id'];
662 $announce_object_data['object_type'] = $object_data['object_type'];
663 $announce_object_data['push'] = $push;
666 $announce_object_data['raw'] = $body;
669 ActivityPub\Processor::createActivity($fetchQueue, $announce_object_data, Activity::ANNOUNCE);
671 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
676 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
677 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::LIKE);
678 } elseif ($object_data['object_type'] == '') {
679 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
681 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
686 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
687 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::DISLIKE);
688 } elseif ($object_data['object_type'] == '') {
689 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
691 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
695 case 'as:TentativeAccept':
696 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
697 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTENDMAYBE);
699 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
704 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
705 ActivityPub\Processor::updateItem($fetchQueue, $object_data);
706 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
707 ActivityPub\Processor::updatePerson($object_data);
708 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
709 // Unhandled Peertube activity
710 self::removeFromQueue($object_data);
712 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
717 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
718 ActivityPub\Processor::deleteItem($object_data);
719 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
720 ActivityPub\Processor::deletePerson($object_data);
721 } elseif ($object_data['object_type'] == '') {
722 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
724 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
729 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
730 ActivityPub\Processor::blockAccount($object_data);
732 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
737 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
738 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
739 } elseif ($object_data['object_type'] == '') {
740 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
742 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
747 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
748 ActivityPub\Processor::followUser($object_data);
749 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
750 $object_data['reply-to-id'] = $object_data['object_id'];
751 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::FOLLOW);
753 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
758 if ($object_data['object_type'] == 'as:Follow') {
759 ActivityPub\Processor::acceptFollowUser($object_data);
760 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
761 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTEND);
763 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
768 if ($object_data['object_type'] == 'as:Follow') {
769 ActivityPub\Processor::rejectFollowUser($object_data);
770 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
771 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::ATTENDNO);
773 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
778 if (($object_data['object_type'] == 'as:Follow') &&
779 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
780 ActivityPub\Processor::undoFollowUser($object_data);
781 } elseif (($object_data['object_type'] == 'as:Follow') &&
782 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
783 ActivityPub\Processor::undoActivity($object_data);
784 } elseif (($object_data['object_type'] == 'as:Accept') &&
785 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
786 ActivityPub\Processor::rejectFollowUser($object_data);
787 } elseif (($object_data['object_type'] == 'as:Block') &&
788 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
789 ActivityPub\Processor::unblockAccount($object_data);
790 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
791 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
792 ActivityPub\Processor::undoActivity($object_data);
793 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
794 empty($object_data['object_object_type'])) {
795 // We cannot detect the target object. So we can ignore it.
796 self::removeFromQueue($object_data);
797 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
798 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
799 // Unhandled Peertube activity
800 self::removeFromQueue($object_data);
802 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
807 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
808 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::VIEW);
809 } elseif ($object_data['object_type'] == '') {
810 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
811 self::removeFromQueue($object_data);
813 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
817 case 'litepub:EmojiReact':
818 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
819 ActivityPub\Processor::createActivity($fetchQueue, $object_data, Activity::EMOJIREACT);
820 } elseif ($object_data['object_type'] == '') {
821 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
823 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
828 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
829 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
835 * Stores unhandled or unknown Activities as a file
837 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
838 * @param string $type Activity type
839 * @param array $object_data Preprocessed array that is generated out of the received activity
840 * @param array $activity Array with activity data
841 * @param string $body The unprocessed body
842 * @param integer $uid User ID
843 * @param boolean $trust_source Do we trust the source?
844 * @param boolean $push Message had been pushed to our system
845 * @param array $signer The signer of the post
848 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 = [])
850 if (!DI::config()->get('debug', 'ap_log_unknown')) {
851 self::removeFromQueue($activity);
855 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
857 if (!empty($object_data['object_type'])) {
858 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
861 if (!empty($object_data['object_object_type'])) {
862 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
865 $tempfile = tempnam(System::getTempPath(), $file);
866 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));
867 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
871 * Fetch a user id from an activity array
873 * @param array $activity
874 * @param string $actor
876 * @return int user id
878 public static function getBestUserForActivity(array $activity): int
881 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
883 $receivers = self::getReceivers($activity, $actor);
884 foreach ($receivers as $receiver) {
885 if ($receiver['type'] == self::TARGET_GLOBAL) {
888 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
889 $uid = $receiver['uid'];
893 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
895 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
896 if (!empty($contact['uid'])) {
897 $uid = $contact['uid'];
904 // @TODO Missing documentation
905 public static function getReceiverURL(array $activity): array
909 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
910 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
911 if (empty($receiver_list)) {
915 foreach ($receiver_list as $receiver) {
916 if ($receiver == self::PUBLIC_COLLECTION) {
917 $receiver = ActivityPub::PUBLIC_COLLECTION;
919 $urls[$element][] = $receiver;
927 * Fetch the receiver list from an activity array
929 * @param array $activity
930 * @param string $actor
932 * @param boolean $fetch_unlisted
934 * @return array with receivers (user id)
937 private static function getReceivers(array $activity, string $actor, array $tags = [], bool $fetch_unlisted = false): array
939 $reply = $receivers = $profile = [];
941 // When it is an answer, we inherite the receivers from the parent
942 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
943 if (!empty($replyto)) {
946 // Fix possibly wrong item URI (could be an answer to a plink uri)
947 $fixedReplyTo = Item::getURIByLink($replyto);
948 if (!empty($fixedReplyTo)) {
949 $reply[] = $fixedReplyTo;
953 // Fetch all posts that refer to the object id
954 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
955 if (!empty($object_id)) {
956 $reply[] = $object_id;
959 if (!empty($reply)) {
960 $parents = Post::select(['uid'], ['uri' => $reply]);
961 while ($parent = Post::fetch($parents)) {
962 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
964 DBA::close($parents);
967 if (!empty($actor)) {
968 $profile = APContact::getByURL($actor);
969 $followers = $profile['followers'] ?? '';
970 $is_forum = ($actor['type'] ?? '') == 'Group';
971 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
973 Logger::info('Empty actor', ['activity' => $activity]);
978 // We have to prevent false follower assumptions upon thread completions
979 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
981 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
982 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
983 if (empty($receiver_list)) {
987 foreach ($receiver_list as $receiver) {
988 if ($receiver == self::PUBLIC_COLLECTION) {
989 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
992 // Add receiver "-1" for unlisted posts
993 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
994 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
997 // Fetch the receivers for the public and the followers collection
998 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
999 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
1003 // Fetching all directly addressed receivers
1004 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
1005 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
1006 if (!DBA::isResult($contact)) {
1010 // Check if the potential receiver is following the actor
1011 // Exception: The receiver is targetted via "to" or this is a comment
1012 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
1013 $networks = Protocol::FEDERATED;
1014 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1015 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
1017 // Forum posts are only accepted from forum contacts
1018 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
1019 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
1022 if (!DBA::exists('contact', $condition)) {
1027 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
1028 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
1031 $type = self::TARGET_TO;
1034 $type = self::TARGET_CC;
1037 $type = self::TARGET_BTO;
1040 $type = self::TARGET_BCC;
1044 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
1049 self::switchContacts($receivers, $actor);
1055 * Fetch the receiver list of a given actor
1057 * @param string $actor
1058 * @param array $tags
1059 * @param array $receivers
1060 * @param integer $target_type
1061 * @param array $profile
1063 * @return array with receivers (user id)
1064 * @throws \Exception
1066 private static function getReceiverForActor(string $actor, array $tags, array $receivers, int $target_type, array $profile): array
1068 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1069 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1071 if (!empty($profile['uri-id'])) {
1072 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1073 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1074 while ($contact = DBA::fetch($contacts)) {
1075 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1076 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1079 DBA::close($contacts);
1081 // This part will only be called while post update 1426 wasn't finished
1082 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1083 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1084 while ($contact = DBA::fetch($contacts)) {
1085 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1086 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1089 DBA::close($contacts);
1091 // The queries are split because of performance issues
1092 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1093 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1094 while ($contact = DBA::fetch($contacts)) {
1095 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1096 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1099 DBA::close($contacts);
1105 * Tests if the contact is a valid receiver for this actor
1107 * @param array $contact
1108 * @param array $tags
1110 * @return bool with receivers (user id)
1111 * @throws \Exception
1113 private static function isValidReceiverForActor(array $contact, array $tags): bool
1115 // Are we following the contact? Then this is a valid receiver
1116 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1120 // When the possible receiver isn't a community, then it is no valid receiver
1121 $owner = User::getOwnerDataById($contact['uid']);
1122 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1126 // Is the community account tagged?
1127 foreach ($tags as $tag) {
1128 if ($tag['type'] != 'Mention') {
1132 if (Strings::compareLink($tag['href'], $owner['url'])) {
1141 * Switches existing contacts to ActivityPub
1143 * @param integer $cid Contact ID
1144 * @param integer $uid User ID
1145 * @param string $url Profile URL
1147 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1148 * @throws \ImagickException
1150 public static function switchContact(int $cid, int $uid, string $url)
1152 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1153 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1157 if (Contact::updateFromProbe($cid)) {
1158 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1161 // Send a new follow request to be sure that the connection still exists
1162 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1163 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1164 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1169 * @TODO Fix documentation and type-hints
1174 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1175 * @throws \ImagickException
1177 private static function switchContacts($receivers, $actor)
1179 if (empty($actor)) {
1183 foreach ($receivers as $receiver) {
1184 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1185 if (DBA::isResult($contact)) {
1186 self::switchContact($contact['id'], $receiver['uid'], $actor);
1189 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1190 if (DBA::isResult($contact)) {
1191 self::switchContact($contact['id'], $receiver['uid'], $actor);
1197 * @TODO Fix documentation and type-hints
1199 * @param $object_data
1200 * @param array $activity
1204 private static function addActivityFields($object_data, array $activity)
1206 if (!empty($activity['published']) && empty($object_data['published'])) {
1207 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1210 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1211 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1214 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1215 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1217 if (!empty($object_data['object_id'])) {
1218 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1219 $objectId = Item::getURIByLink($object_data['object_id']);
1220 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1221 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1222 $object_data['object_id'] = $objectId;
1226 return $object_data;
1230 * Fetches the object data from external ressources if needed
1232 * @param string $object_id Object ID of the the provided object
1233 * @param array $object The provided object array
1234 * @param boolean $trust_source Do we trust the provided object?
1235 * @param integer $uid User ID for the signature that we use to fetch data
1237 * @return array|false with trusted and valid object data
1238 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1239 * @throws \ImagickException
1241 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1243 // By fetching the type we check if the object is complete.
1244 $type = JsonLD::fetchElement($object, '@type');
1246 if (!$trust_source || empty($type)) {
1247 $data = ActivityPub::fetchContent($object_id, $uid);
1248 if (!empty($data)) {
1249 $object = JsonLD::compact($data);
1250 Logger::info('Fetched content for ' . $object_id);
1252 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1254 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1255 if (!DBA::isResult($item)) {
1256 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1259 Logger::info('Using already stored item for url ' . $object_id);
1260 $data = ActivityPub\Transmitter::createNote($item);
1261 $object = JsonLD::compact($data);
1264 $id = JsonLD::fetchElement($object, '@id');
1266 Logger::info('Empty id');
1270 if ($id != $object_id) {
1271 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1275 Logger::info('Using original object for url ' . $object_id);
1278 $type = JsonLD::fetchElement($object, '@type');
1280 Logger::info('Empty type');
1284 // Lemmy is resharing "create" activities instead of content
1285 // We fetch the content from the activity.
1286 if (in_array($type, ['as:Create'])) {
1287 $object = $object['as:object'];
1288 $type = JsonLD::fetchElement($object, '@type');
1290 Logger::info('Empty type');
1293 $object_data = self::processObject($object);
1296 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1297 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1298 $object_data = self::processObject($object);
1300 if (!empty($data)) {
1301 $object_data['raw'] = json_encode($data);
1303 return $object_data;
1306 if ($type == 'as:Announce') {
1307 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1308 if (empty($object_id) || !is_string($object_id)) {
1311 return self::fetchObject($object_id, [], false, $uid);
1314 Logger::info('Unhandled object type: ' . $type);
1319 * Converts the language element (Used by Peertube)
1321 * @param array $languages
1322 * @return array Languages
1324 public static function processLanguages(array $languages): array
1326 if (empty($languages)) {
1330 $language_list = [];
1332 foreach ($languages as $language) {
1333 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1334 $language_list[$language['_:identifier']] = $language['as:name'];
1337 return $language_list;
1341 * Convert tags from JSON-LD format into a simplified format
1343 * @param array $tags Tags in JSON-LD format
1345 * @return array with tags in a simplified format
1347 public static function processTags(array $tags): array
1351 foreach ($tags as $tag) {
1356 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1357 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1358 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1360 if (empty($element['type'])) {
1364 if (empty($element['href'])) {
1365 $element['href'] = $element['name'];
1368 $taglist[] = $element;
1374 * Convert emojis from JSON-LD format into a simplified format
1376 * @param array $emojis
1377 * @return array with emojis in a simplified format
1379 private static function processEmojis(array $emojis): array
1383 foreach ($emojis as $emoji) {
1384 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1388 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1389 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1392 $emojilist[] = $element;
1399 * Convert attachments from JSON-LD format into a simplified format
1401 * @param array $attachments Attachments in JSON-LD format
1403 * @return array Attachments in a simplified format
1405 private static function processAttachments(array $attachments): array
1409 // Removes empty values
1410 $attachments = array_filter($attachments);
1412 foreach ($attachments as $attachment) {
1413 switch (JsonLD::fetchElement($attachment, '@type')) {
1418 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1419 foreach ($urls as $url) {
1420 // Single scalar URL case
1421 if (is_string($url)) {
1426 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1427 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1428 if (Strings::startsWith($mediaType, 'image')) {
1437 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1438 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1440 'image' => $pageImage,
1444 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1445 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1446 $imagePreviewUrl = null;
1448 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1449 $imageVariants = [];
1450 $previewVariants = [];
1451 foreach ($urls as $url) {
1452 // Scalar URL, no discrimination possible
1453 if (is_string($url)) {
1454 $imageFullUrl = $url;
1458 // Not sure what to do with a different Link media type than the base Image, we skip
1459 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1463 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1465 // Default URL choice if no discriminating width is provided
1466 $imageFullUrl = $href ?? $imageFullUrl;
1468 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1470 if ($href && $width) {
1471 $imageVariants[$width] = $href;
1472 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1473 $previewVariants[abs(632 - $width)] = $href;
1477 if ($imageVariants) {
1478 // Taking the maximum size image
1479 ksort($imageVariants);
1480 $imageFullUrl = array_pop($imageVariants);
1482 // Taking the minimum number distance to the target distance
1483 ksort($previewVariants);
1484 $imagePreviewUrl = array_shift($previewVariants);
1487 unset($imageVariants);
1488 unset($previewVariants);
1492 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1493 'mediaType' => $mediaType,
1494 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1495 'url' => $imageFullUrl,
1496 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1501 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1502 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1503 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1504 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1505 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1506 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1507 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1516 * Convert questions from JSON-LD format into a simplified format
1518 * @param array $object
1520 * @return array Questions in a simplified format
1522 private static function processQuestion(array $object): array
1526 if (!empty($object['as:oneOf'])) {
1527 $question['multiple'] = false;
1528 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1529 } elseif (!empty($object['as:anyOf'])) {
1530 $question['multiple'] = true;
1531 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1536 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1537 if (!empty($closed)) {
1538 $question['end-time'] = $closed;
1540 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1543 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1544 $question['options'] = [];
1548 foreach ($options as $option) {
1549 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1553 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1555 if (empty($option['as:replies'])) {
1559 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1561 $question['options'][] = ['name' => $name, 'replies' => $replies];
1563 $voters += (int)$replies;
1566 // For single choice question we can count the number of voters if not provided (like with Misskey)
1567 if (empty($question['voters']) && !$question['multiple']) {
1568 $question['voters'] = $voters;
1575 * Fetch the original source or content with the "language" Markdown or HTML
1577 * @param array $object
1578 * @param array $object_data
1580 * @return array Object data (?)
1581 * @throws \Exception
1583 private static function getSource(array $object, array $object_data): array
1585 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1586 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1587 if (!empty($object_data['source'])) {
1588 return $object_data;
1591 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1592 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1593 if (!empty($object_data['source'])) {
1594 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1595 return $object_data;
1598 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1599 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1600 if (!empty($object_data['source'])) {
1601 $object_data['source'] = HTML::toBBCode($object_data['source']);
1602 return $object_data;
1605 return $object_data;
1609 * Extracts a potential alternate URL from a list of additional URL elements
1611 * @param array $urls
1614 private static function extractAlternateUrl(array $urls): string
1617 foreach ($urls as $key => $url) {
1618 // Not a list but a single URL element
1619 if (!is_numeric($key)) {
1623 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1627 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1632 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1633 if (empty($mediatype)) {
1637 if ($mediatype == 'text/html') {
1638 $alternateUrl = $href;
1642 return $alternateUrl;
1646 * Check if the "as:url" element is an array with multiple links
1647 * This is the case with audio and video posts.
1648 * Then the links are added as attachments
1650 * @param array $urls The object URL list
1651 * @return array an array of attachments
1653 private static function processAttachmentUrls(array $urls): array
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 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1678 if ($filetype == 'audio') {
1679 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1680 } elseif ($filetype == 'video') {
1681 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1682 // PeerTube audio-only track
1683 if ($height === 0) {
1687 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1688 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1689 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1690 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1692 // For Torrent links we always store the highest resolution
1693 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1697 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1698 } elseif ($mediatype == 'application/x-mpegURL') {
1699 // PeerTube exception, actual video link is in the tags of this URL element
1700 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1704 return array_values($attachments);
1708 * Fetches data from the object part of an activity
1710 * @param array $object
1712 * @return array|bool Object data or FALSE if $object does not contain @id element
1713 * @throws \Exception
1715 private static function processObject(array $object)
1717 if (!JsonLD::fetchElement($object, '@id')) {
1722 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1723 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1724 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1726 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1727 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1728 $object_data['reply-to-id'] = $object_data['id'];
1730 // On activities the "reply to" is the id of the object it refers to
1731 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1732 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1733 if (!empty($object_id)) {
1734 $object_data['reply-to-id'] = $object_id;
1738 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1739 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1740 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1741 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1742 $object_data['reply-to-id'] = $replyToId;
1746 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1747 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1749 if (empty($object_data['updated'])) {
1750 $object_data['updated'] = $object_data['published'];
1753 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1754 $object_data['published'] = $object_data['updated'];
1757 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1758 if (empty($actor)) {
1759 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1762 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1763 $location = JsonLD::fetchElement($location, 'location', '@value');
1765 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1766 // down to HTML and then finally format to plaintext.
1767 $location = Markdown::convert($location);
1768 $location = BBCode::toPlaintext($location);
1771 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1772 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1773 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1774 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1775 $object_data['actor'] = $object_data['author'] = $actor;
1776 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1777 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1778 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1779 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1780 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1781 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1782 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1783 $object_data = self::getSource($object, $object_data);
1784 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1785 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1786 $object_data['location'] = $location;
1787 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1788 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1789 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1790 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1791 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1792 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1793 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1794 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1795 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1796 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1797 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1799 // Special treatment for Hubzilla links
1800 if (is_array($object_data['alternate-url'])) {
1801 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1803 if (!is_string($object_data['alternate-url'])) {
1804 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1808 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1809 $object_data['alternate-url'] = null;
1812 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1813 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1814 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1817 // For page types we expect that the alternate url posts to some page.
1818 // So we add this to the attachments if it differs from the id.
1819 // Currently only Lemmy is using the page type.
1820 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1821 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1822 $object_data['alternate-url'] = null;
1825 if ($object_data['object_type'] == 'as:Question') {
1826 $object_data['question'] = self::processQuestion($object);
1829 $receiverdata = self::getReceivers($object, $object_data['actor'] ?? '', $object_data['tags'], true);
1830 $receivers = $reception_types = [];
1831 foreach ($receiverdata as $key => $data) {
1832 $receivers[$key] = $data['uid'];
1833 $reception_types[$data['uid']] = $data['type'] ?? 0;
1836 $object_data['receiver_urls'] = self::getReceiverURL($object);
1837 $object_data['receiver'] = $receivers;
1838 $object_data['reception_type'] = $reception_types;
1840 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1841 unset($object_data['receiver'][-1]);
1842 unset($object_data['reception_type'][-1]);
1844 // Common object data:
1847 // @context, type, actor, signature, mediaType, duration, replies, icon
1849 // Also missing: (Defined in the standard, but currently unused)
1850 // audience, preview, endTime, startTime, image
1855 // contentMap, announcement_count, announcements, context_id, likes, like_count
1856 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1861 // category, licence, language, commentsEnabled
1864 // views, waitTranscoding, state, support, subtitleLanguage
1865 // likes, dislikes, shares, comments
1867 return $object_data;