3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Text\BBCode;
25 use Friendica\Database\DBA;
26 use Friendica\Content\Text\HTML;
27 use Friendica\Content\Text\Markdown;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
32 use Friendica\Model\Contact;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\User;
37 use Friendica\Protocol\Activity;
38 use Friendica\Protocol\ActivityPub;
39 use Friendica\Util\HTTPSignature;
40 use Friendica\Util\JsonLD;
41 use Friendica\Util\LDSignature;
42 use Friendica\Util\Network;
43 use Friendica\Util\Strings;
46 * ActivityPub Receiver Protocol class
51 * Check what this is meant to do:
60 const PUBLIC_COLLECTION = 'as:Public';
61 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
62 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
63 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
65 const TARGET_UNKNOWN = 0;
70 const TARGET_FOLLOWER = 5;
71 const TARGET_ANSWER = 6;
72 const TARGET_GLOBAL = 7;
74 const COMPLETION_NONE = 0;
75 const COMPLETION_ANNOUCE = 1;
76 const COMPLETION_RELAY = 2;
77 const COMPLETION_MANUAL = 3;
78 const COMPLETION_AUTO = 4;
81 * Checks incoming message from the inbox
85 * @param integer $uid User ID
88 public static function processInbox($body, $header, $uid)
90 $activity = json_decode($body, true);
91 if (empty($activity)) {
92 Logger::warning('Invalid body.');
96 $ldactivity = JsonLD::compact($activity);
98 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
100 $apcontact = APContact::getByURL($actor);
101 if (empty($apcontact)) {
102 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
104 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
105 self::processRelayPost($ldactivity, $actor);
108 APContact::unmarkForArchival($apcontact);
111 $http_signer = HTTPSignature::getSigner($body, $header);
112 if ($http_signer === false) {
113 Logger::warning('Invalid HTTP signature, message will be discarded.');
115 } elseif (empty($http_signer)) {
116 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
119 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
122 $signer = [$http_signer];
124 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
126 if (LDSignature::isSigned($activity)) {
127 $ld_signer = LDSignature::getSigner($activity);
128 if (empty($ld_signer)) {
129 Logger::info('Invalid JSON-LD signature from ' . $actor);
130 } elseif ($ld_signer != $http_signer) {
131 $signer[] = $ld_signer;
133 if (!empty($ld_signer && ($actor == $http_signer))) {
134 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
135 $trust_source = true;
136 } elseif (!empty($ld_signer)) {
137 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
138 $trust_source = true;
139 } elseif ($actor == $http_signer) {
140 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
141 $trust_source = true;
143 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
144 $trust_source = false;
146 } elseif ($actor == $http_signer) {
147 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
148 $trust_source = true;
150 Logger::info('No JSON-LD signature, different actor.');
151 $trust_source = false;
154 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
158 * Process incoming posts from relays
160 * @param array $activity
161 * @param string $actor
164 private static function processRelayPost(array $activity, string $actor)
166 $type = JsonLD::fetchElement($activity, '@type');
168 Logger::info('Empty type', ['activity' => $activity]);
172 if ($type != 'as:Announce') {
173 Logger::info('Not an announcement', ['activity' => $activity]);
177 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
178 if (empty($object_id)) {
179 Logger::info('No object id found', ['activity' => $activity]);
183 $contact = Contact::getByURL($actor);
184 if (empty($contact)) {
185 Logger::info('Relay contact not found', ['actor' => $actor]);
189 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
190 Logger::notice('Relay is no sharer', ['actor' => $actor]);
194 Logger::info('Got relayed message id', ['id' => $object_id]);
196 $item_id = Item::searchByLink($object_id);
198 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
202 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
204 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
208 $item_id = Item::searchByLink($object_id);
210 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
212 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
217 * Fetches the object type for a given object id
219 * @param array $activity
220 * @param string $object_id Object ID of the the provided object
221 * @param integer $uid User ID
223 * @return string with object type
224 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
225 * @throws \ImagickException
227 private static function fetchObjectType($activity, $object_id, $uid = 0)
229 if (!empty($activity['as:object'])) {
230 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
231 if (!empty($object_type)) {
236 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
237 // We just assume "note" since it doesn't make a difference for the further processing
241 $profile = APContact::getByURL($object_id);
242 if (!empty($profile['type'])) {
243 APContact::unmarkForArchival($profile);
244 return 'as:' . $profile['type'];
247 $data = ActivityPub::fetchContent($object_id, $uid);
249 $object = JsonLD::compact($data);
250 $type = JsonLD::fetchElement($object, '@type');
260 * Prepare the object array
262 * @param array $activity Array with activity data
263 * @param integer $uid User ID
264 * @param boolean $push Message had been pushed to our system
265 * @param boolean $trust_source Do we trust the source?
267 * @return array with object data
268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
269 * @throws \ImagickException
271 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
273 $id = JsonLD::fetchElement($activity, '@id');
274 if (!empty($id) && !$trust_source) {
275 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
277 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
278 if (!empty($fetched_activity)) {
279 $object = JsonLD::compact($fetched_activity);
280 $fetched_id = JsonLD::fetchElement($object, '@id');
281 if ($fetched_id == $id) {
282 Logger::info('Activity had been fetched successfully', ['id' => $id]);
283 $trust_source = true;
286 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
289 Logger::info('Activity could not been fetched', ['id' => $id]);
293 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
295 Logger::info('Empty actor', ['activity' => $activity]);
299 $type = JsonLD::fetchElement($activity, '@type');
301 // Fetch all receivers from to, cc, bto and bcc
302 $receiverdata = self::getReceivers($activity, $actor);
303 $receivers = $reception_types = [];
304 foreach ($receiverdata as $key => $data) {
305 $receivers[$key] = $data['uid'];
306 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
309 $urls = self::getReceiverURL($activity);
311 // When it is a delivery to a personal inbox we add that user to the receivers
313 $additional = [$uid => $uid];
314 $receivers = array_replace($receivers, $additional);
315 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]))) {
316 $reception_types[$uid] = self::TARGET_BCC;
317 $owner = User::getOwnerDataById($uid);
318 if (!empty($owner['url'])) {
319 $urls['as:bcc'][] = $owner['url'];
324 // We possibly need some user to fetch private content,
325 // so we fetch one out of the receivers if no uid is provided.
326 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
328 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
329 if (empty($object_id)) {
330 Logger::info('No object found');
334 if (!is_string($object_id)) {
335 Logger::info('Invalid object id', ['object' => $object_id]);
339 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
341 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
342 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
343 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
345 $type = $object_type;
346 $activity = JsonLD::compact($data);
348 // Some variables need to be refetched since the activity changed
349 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
350 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
351 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
355 // Any activities on account types must not be altered
356 if (in_array($object_type, self::ACCOUNT_TYPES)) {
358 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
359 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
360 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
361 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
362 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
363 $object_data['push'] = $push;
364 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
365 // Fetch the content only on activities where this matters
366 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
367 // Always fetch on "Announce"
368 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
369 if (empty($object_data)) {
370 Logger::info("Object data couldn't be processed");
374 $object_data['object_id'] = $object_id;
376 if ($type == 'as:Announce') {
377 $object_data['push'] = false;
379 $object_data['push'] = $push;
382 // Test if it is an answer to a mail
383 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
384 $object_data['directmessage'] = true;
386 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
388 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact', 'as:View'])) && in_array($object_type, self::CONTENT_TYPES)) {
389 // Create a mostly empty array out of the activity data (instead of the object).
390 // This way we later don't have to check for the existence of each individual array element.
391 $object_data = self::processObject($activity);
392 $object_data['name'] = $type;
393 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
394 $object_data['object_id'] = $object_id;
395 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
396 $object_data['push'] = $push;
397 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
399 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
400 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
401 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
402 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
403 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
404 $object_data['push'] = $push;
407 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
408 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
409 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
410 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
411 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
412 $object_data['push'] = $push;
414 // An Undo is done on the object of an object, so we need that type as well
415 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
416 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
420 $object_data = self::addActivityFields($object_data, $activity);
422 if (empty($object_data['object_type'])) {
423 $object_data['object_type'] = $object_type;
426 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
427 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
428 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
432 $object_data['type'] = $type;
433 $object_data['actor'] = $actor;
434 $object_data['item_receiver'] = $receivers;
435 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
436 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
438 $author = $object_data['author'] ?? $actor;
439 if (!empty($author) && !empty($object_data['id'])) {
440 $author_host = parse_url($author, PHP_URL_HOST);
441 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
442 if ($author_host == $id_host) {
443 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
445 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
446 $trust_source = false;
450 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
456 * Fetches the first user id from the receiver array
458 * @param array $receivers Array with receivers
459 * @return integer user id;
461 public static function getFirstUserFromReceivers($receivers)
463 foreach ($receivers as $receiver) {
464 if (!empty($receiver)) {
472 * Processes the activity object
474 * @param array $activity Array with activity data
475 * @param string $body The unprocessed body
476 * @param integer $uid User ID
477 * @param boolean $trust_source Do we trust the source?
478 * @param boolean $push Message had been pushed to our system
479 * @param array $signer The signer of the post
482 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
484 $type = JsonLD::fetchElement($activity, '@type');
486 Logger::info('Empty type', ['activity' => $activity]);
490 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
491 Logger::info('Empty object', ['activity' => $activity]);
495 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
497 Logger::info('Empty actor', ['activity' => $activity]);
501 if (is_array($activity['as:object'])) {
502 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
507 // Test the provided signatures against the actor and "attributedTo"
509 if (!empty($attributed_to) && !empty($actor)) {
510 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
512 $trust_source = in_array($actor, $signer);
516 // $trust_source is called by reference and is set to true if the content was retrieved successfully
517 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
518 if (empty($object_data)) {
519 Logger::info('No object data found', ['activity' => $activity]);
523 // Lemmy is announcing activities.
524 // We are changing the announces into regular activities.
525 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
526 $type = $object_data['type'];
529 if (!$trust_source) {
530 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
534 if (!empty($body) && empty($object_data['raw'])) {
535 $object_data['raw'] = $body;
538 // Internal flag for thread completion. See Processor.php
539 if (!empty($activity['thread-completion'])) {
540 $object_data['thread-completion'] = $activity['thread-completion'];
543 if (!empty($activity['completion-mode'])) {
544 $object_data['completion-mode'] = $activity['completion-mode'];
547 if (!empty($activity['thread-children-type'])) {
548 $object_data['thread-children-type'] = $activity['thread-children-type'];
551 // Internal flag for posts that arrived via relay
552 if (!empty($activity['from-relay'])) {
553 $object_data['from-relay'] = $activity['from-relay'];
556 if (in_array('as:Question', [$object_data['object_type'] ?? '', $object_data['object_object_type'] ?? ''])) {
557 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
562 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
563 $item = ActivityPub\Processor::createItem($object_data);
564 ActivityPub\Processor::postItem($object_data, $item);
565 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
566 // Unhandled Peertube activity
568 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
573 if (in_array($object_data['object_type'], ['as:Event'])) {
574 $item = ActivityPub\Processor::createItem($object_data);
575 ActivityPub\Processor::postItem($object_data, $item);
577 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
582 if ($object_data['object_type'] == 'as:tag') {
583 ActivityPub\Processor::addTag($object_data);
584 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
585 ActivityPub\Processor::addToFeaturedCollection($object_data);
586 } elseif ($object_data['object_type'] == '') {
587 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
589 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
594 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
595 $object_data['thread-completion'] = Contact::getIdForURL($actor);
596 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
598 $item = ActivityPub\Processor::createItem($object_data);
603 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
604 ActivityPub\Processor::postItem($object_data, $item);
606 $announce_object_data = self::processObject($activity);
607 $announce_object_data['name'] = $type;
608 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
609 $announce_object_data['object_id'] = $object_data['object_id'];
610 $announce_object_data['object_type'] = $object_data['object_type'];
611 $announce_object_data['push'] = $push;
614 $announce_object_data['raw'] = $body;
617 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
619 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
624 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
625 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
626 } elseif ($object_data['object_type'] == '') {
627 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
629 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
634 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
635 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
636 } elseif ($object_data['object_type'] == '') {
637 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
639 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
643 case 'as:TentativeAccept':
644 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
645 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
647 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
652 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
653 ActivityPub\Processor::updateItem($object_data);
654 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
655 ActivityPub\Processor::updatePerson($object_data);
656 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
657 // Unhandled Peertube activity
659 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
664 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
665 ActivityPub\Processor::deleteItem($object_data);
666 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
667 ActivityPub\Processor::deletePerson($object_data);
668 } elseif ($object_data['object_type'] == '') {
669 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
671 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
676 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
677 ActivityPub\Processor::blockAccount($object_data);
679 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
684 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
685 ActivityPub\Processor::removeFromFeaturedCollection($object_data);
686 } elseif ($object_data['object_type'] == '') {
687 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
689 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
694 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
695 ActivityPub\Processor::followUser($object_data);
696 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
697 $object_data['reply-to-id'] = $object_data['object_id'];
698 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
700 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
705 if ($object_data['object_type'] == 'as:Follow') {
706 ActivityPub\Processor::acceptFollowUser($object_data);
707 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
708 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
710 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
715 if ($object_data['object_type'] == 'as:Follow') {
716 ActivityPub\Processor::rejectFollowUser($object_data);
717 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
718 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
720 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
725 if (($object_data['object_type'] == 'as:Follow') &&
726 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
727 ActivityPub\Processor::undoFollowUser($object_data);
728 } elseif (($object_data['object_type'] == 'as:Follow') &&
729 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
730 ActivityPub\Processor::undoActivity($object_data);
731 } elseif (($object_data['object_type'] == 'as:Accept') &&
732 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
733 ActivityPub\Processor::rejectFollowUser($object_data);
734 } elseif (($object_data['object_type'] == 'as:Block') &&
735 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
736 ActivityPub\Processor::unblockAccount($object_data);
737 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
738 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
739 ActivityPub\Processor::undoActivity($object_data);
740 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
741 empty($object_data['object_object_type'])) {
742 // We cannot detect the target object. So we can ignore it.
743 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
744 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
745 // Unhandled Peertube activity
747 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
752 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
753 ActivityPub\Processor::createActivity($object_data, Activity::VIEW);
754 } elseif ($object_data['object_type'] == '') {
755 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
757 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
761 case 'litepub:EmojiReact':
762 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
763 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
764 } elseif ($object_data['object_type'] == '') {
765 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
767 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
772 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
773 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
779 * Stores unhandled or unknown Activities as a file
781 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
782 * @param string $type Activity type
783 * @param array $object_data Preprocessed array that is generated out of the received activity
784 * @param array $activity Array with activity data
785 * @param string $body The unprocessed body
786 * @param integer $uid User ID
787 * @param boolean $trust_source Do we trust the source?
788 * @param boolean $push Message had been pushed to our system
789 * @param array $signer The signer of the post
792 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 = [])
794 if (!DI::config()->get('debug', 'ap_log_unknown')) {
798 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
800 if (!empty($object_data['object_type'])) {
801 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
804 if (!empty($object_data['object_object_type'])) {
805 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
808 $tempfile = tempnam(System::getTempPath(), $file);
809 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));
810 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
814 * Fetch a user id from an activity array
816 * @param array $activity
817 * @param string $actor
819 * @return int user id
821 public static function getBestUserForActivity(array $activity)
824 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
826 $receivers = self::getReceivers($activity, $actor);
827 foreach ($receivers as $receiver) {
828 if ($receiver['type'] == self::TARGET_GLOBAL) {
831 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
832 $uid = $receiver['uid'];
836 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
838 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
839 if (!empty($contact['uid'])) {
840 $uid = $contact['uid'];
847 public static function getReceiverURL($activity)
851 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
852 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
853 if (empty($receiver_list)) {
857 foreach ($receiver_list as $receiver) {
858 if ($receiver == self::PUBLIC_COLLECTION) {
859 $receiver = ActivityPub::PUBLIC_COLLECTION;
861 $urls[$element][] = $receiver;
869 * Fetch the receiver list from an activity array
871 * @param array $activity
872 * @param string $actor
874 * @param boolean $fetch_unlisted
876 * @return array with receivers (user id)
879 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
881 $reply = $receivers = [];
883 // When it is an answer, we inherite the receivers from the parent
884 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
885 if (!empty($replyto)) {
888 // Fix possibly wrong item URI (could be an answer to a plink uri)
889 $fixedReplyTo = Item::getURIByLink($replyto);
890 if (!empty($fixedReplyTo)) {
891 $reply[] = $fixedReplyTo;
895 // Fetch all posts that refer to the object id
896 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
897 if (!empty($object_id)) {
898 $reply[] = $object_id;
901 if (!empty($reply)) {
902 $parents = Post::select(['uid'], ['uri' => $reply]);
903 while ($parent = Post::fetch($parents)) {
904 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
906 DBA::close($parents);
909 if (!empty($actor)) {
910 $profile = APContact::getByURL($actor);
911 $followers = $profile['followers'] ?? '';
912 $is_forum = ($actor['type'] ?? '') == 'Group';
913 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
915 Logger::info('Empty actor', ['activity' => $activity]);
920 // We have to prevent false follower assumptions upon thread completions
921 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
923 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
924 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
925 if (empty($receiver_list)) {
929 foreach ($receiver_list as $receiver) {
930 if ($receiver == self::PUBLIC_COLLECTION) {
931 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
934 // Add receiver "-1" for unlisted posts
935 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
936 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
939 // Fetch the receivers for the public and the followers collection
940 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
941 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target, $profile);
945 // Fetching all directly addressed receivers
946 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
947 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
948 if (!DBA::isResult($contact)) {
952 // Check if the potential receiver is following the actor
953 // Exception: The receiver is targetted via "to" or this is a comment
954 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
955 $networks = Protocol::FEDERATED;
956 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
957 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
959 // Forum posts are only accepted from forum contacts
960 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
961 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
964 if (!DBA::exists('contact', $condition)) {
969 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
970 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
973 $type = self::TARGET_TO;
976 $type = self::TARGET_CC;
979 $type = self::TARGET_BTO;
982 $type = self::TARGET_BCC;
986 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
991 self::switchContacts($receivers, $actor);
997 * Fetch the receiver list of a given actor
999 * @param string $actor
1000 * @param array $tags
1001 * @param array $receivers
1002 * @param integer $target_type
1003 * @param array $profile
1005 * @return array with receivers (user id)
1006 * @throws \Exception
1008 private static function getReceiverForActor($actor, $tags, $receivers, $target_type, $profile)
1010 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1011 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1013 if (!empty($profile['uri-id'])) {
1014 $condition = DBA::mergeConditions($basecondition, ["`uri-id` = ? AND `uid` != ?", $profile['uri-id'], 0]);
1015 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1016 while ($contact = DBA::fetch($contacts)) {
1017 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1018 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1021 DBA::close($contacts);
1023 // This part will only be called while post update 1426 wasn't finished
1024 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1025 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1026 while ($contact = DBA::fetch($contacts)) {
1027 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1028 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1031 DBA::close($contacts);
1033 // The queries are split because of performance issues
1034 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1035 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1036 while ($contact = DBA::fetch($contacts)) {
1037 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1038 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1041 DBA::close($contacts);
1047 * Tests if the contact is a valid receiver for this actor
1049 * @param array $contact
1050 * @param string $actor
1051 * @param array $tags
1053 * @return bool with receivers (user id)
1054 * @throws \Exception
1056 private static function isValidReceiverForActor($contact, $tags)
1058 // Are we following the contact? Then this is a valid receiver
1059 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1063 // When the possible receiver isn't a community, then it is no valid receiver
1064 $owner = User::getOwnerDataById($contact['uid']);
1065 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1069 // Is the community account tagged?
1070 foreach ($tags as $tag) {
1071 if ($tag['type'] != 'Mention') {
1075 if (Strings::compareLink($tag['href'], $owner['url'])) {
1084 * Switches existing contacts to ActivityPub
1086 * @param integer $cid Contact ID
1087 * @param integer $uid User ID
1088 * @param string $url Profile URL
1089 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1090 * @throws \ImagickException
1092 public static function switchContact($cid, $uid, $url)
1094 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1095 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1099 if (Contact::updateFromProbe($cid)) {
1100 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1103 // Send a new follow request to be sure that the connection still exists
1104 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1105 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1106 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1115 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1116 * @throws \ImagickException
1118 private static function switchContacts($receivers, $actor)
1120 if (empty($actor)) {
1124 foreach ($receivers as $receiver) {
1125 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1126 if (DBA::isResult($contact)) {
1127 self::switchContact($contact['id'], $receiver['uid'], $actor);
1130 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1131 if (DBA::isResult($contact)) {
1132 self::switchContact($contact['id'], $receiver['uid'], $actor);
1140 * @param $object_data
1141 * @param array $activity
1145 private static function addActivityFields($object_data, $activity)
1147 if (!empty($activity['published']) && empty($object_data['published'])) {
1148 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1151 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1152 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1155 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1156 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1158 if (!empty($object_data['object_id'])) {
1159 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1160 $objectId = Item::getURIByLink($object_data['object_id']);
1161 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1162 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1163 $object_data['object_id'] = $objectId;
1167 return $object_data;
1171 * Fetches the object data from external ressources if needed
1173 * @param string $object_id Object ID of the the provided object
1174 * @param array $object The provided object array
1175 * @param boolean $trust_source Do we trust the provided object?
1176 * @param integer $uid User ID for the signature that we use to fetch data
1178 * @return array|false with trusted and valid object data
1179 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1180 * @throws \ImagickException
1182 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1184 // By fetching the type we check if the object is complete.
1185 $type = JsonLD::fetchElement($object, '@type');
1187 if (!$trust_source || empty($type)) {
1188 $data = ActivityPub::fetchContent($object_id, $uid);
1189 if (!empty($data)) {
1190 $object = JsonLD::compact($data);
1191 Logger::info('Fetched content for ' . $object_id);
1193 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1195 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1196 if (!DBA::isResult($item)) {
1197 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1200 Logger::info('Using already stored item for url ' . $object_id);
1201 $data = ActivityPub\Transmitter::createNote($item);
1202 $object = JsonLD::compact($data);
1205 $id = JsonLD::fetchElement($object, '@id');
1207 Logger::info('Empty id');
1211 if ($id != $object_id) {
1212 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1216 Logger::info('Using original object for url ' . $object_id);
1219 $type = JsonLD::fetchElement($object, '@type');
1221 Logger::info('Empty type');
1225 // Lemmy is resharing "create" activities instead of content
1226 // We fetch the content from the activity.
1227 if (in_array($type, ['as:Create'])) {
1228 $object = $object['as:object'];
1229 $type = JsonLD::fetchElement($object, '@type');
1231 Logger::info('Empty type');
1234 $object_data = self::processObject($object);
1237 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1238 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1239 $object_data = self::processObject($object);
1241 if (!empty($data)) {
1242 $object_data['raw'] = json_encode($data);
1244 return $object_data;
1247 if ($type == 'as:Announce') {
1248 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1249 if (empty($object_id) || !is_string($object_id)) {
1252 return self::fetchObject($object_id, [], false, $uid);
1255 Logger::info('Unhandled object type: ' . $type);
1260 * Converts the language element (Used by Peertube)
1262 * @param array $languages
1263 * @return array Languages
1265 public static function processLanguages(array $languages)
1267 if (empty($languages)) {
1271 $language_list = [];
1273 foreach ($languages as $language) {
1274 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1275 $language_list[$language['_:identifier']] = $language['as:name'];
1278 return $language_list;
1282 * Convert tags from JSON-LD format into a simplified format
1284 * @param array $tags Tags in JSON-LD format
1286 * @return array with tags in a simplified format
1288 public static function processTags(array $tags)
1292 foreach ($tags as $tag) {
1297 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1298 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1299 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1301 if (empty($element['type'])) {
1305 if (empty($element['href'])) {
1306 $element['href'] = $element['name'];
1309 $taglist[] = $element;
1315 * Convert emojis from JSON-LD format into a simplified format
1317 * @param array $emojis
1318 * @return array with emojis in a simplified format
1320 private static function processEmojis(array $emojis)
1324 foreach ($emojis as $emoji) {
1325 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1329 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1330 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1333 $emojilist[] = $element;
1340 * Convert attachments from JSON-LD format into a simplified format
1342 * @param array $attachments Attachments in JSON-LD format
1344 * @return array Attachments in a simplified format
1346 private static function processAttachments(array $attachments)
1350 // Removes empty values
1351 $attachments = array_filter($attachments);
1353 foreach ($attachments as $attachment) {
1354 switch (JsonLD::fetchElement($attachment, '@type')) {
1359 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1360 foreach ($urls as $url) {
1361 // Single scalar URL case
1362 if (is_string($url)) {
1367 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1368 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1369 if (Strings::startsWith($mediaType, 'image')) {
1378 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1379 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1381 'image' => $pageImage,
1385 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1386 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1387 $imagePreviewUrl = null;
1389 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1390 $imageVariants = [];
1391 $previewVariants = [];
1392 foreach ($urls as $url) {
1393 // Scalar URL, no discrimination possible
1394 if (is_string($url)) {
1395 $imageFullUrl = $url;
1399 // Not sure what to do with a different Link media type than the base Image, we skip
1400 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1404 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1406 // Default URL choice if no discriminating width is provided
1407 $imageFullUrl = $href ?? $imageFullUrl;
1409 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1411 if ($href && $width) {
1412 $imageVariants[$width] = $href;
1413 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1414 $previewVariants[abs(632 - $width)] = $href;
1418 if ($imageVariants) {
1419 // Taking the maximum size image
1420 ksort($imageVariants);
1421 $imageFullUrl = array_pop($imageVariants);
1423 // Taking the minimum number distance to the target distance
1424 ksort($previewVariants);
1425 $imagePreviewUrl = array_shift($previewVariants);
1428 unset($imageVariants);
1429 unset($previewVariants);
1433 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1434 'mediaType' => $mediaType,
1435 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1436 'url' => $imageFullUrl,
1437 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1442 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1443 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1444 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1445 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1446 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1447 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1448 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1457 * Convert questions from JSON-LD format into a simplified format
1459 * @param array $object
1461 * @return array Questions in a simplified format
1463 private static function processQuestion(array $object)
1467 if (!empty($object['as:oneOf'])) {
1468 $question['multiple'] = false;
1469 $options = JsonLD::fetchElementArray($object, 'as:oneOf') ?? [];
1470 } elseif (!empty($object['as:anyOf'])) {
1471 $question['multiple'] = true;
1472 $options = JsonLD::fetchElementArray($object, 'as:anyOf') ?? [];
1477 $closed = JsonLD::fetchElement($object, 'as:closed', '@value');
1478 if (!empty($closed)) {
1479 $question['end-time'] = $closed;
1481 $question['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1484 $question['voters'] = (int)JsonLD::fetchElement($object, 'toot:votersCount', '@value');
1485 $question['options'] = [];
1489 foreach ($options as $option) {
1490 if (JsonLD::fetchElement($option, '@type') != 'as:Note') {
1494 $name = JsonLD::fetchElement($option, 'as:name', '@value');
1496 if (empty($option['as:replies'])) {
1500 $replies = JsonLD::fetchElement($option['as:replies'], 'as:totalItems', '@value');
1502 $question['options'][] = ['name' => $name, 'replies' => $replies];
1504 $voters += (int)$replies;
1507 // For single choice question we can count the number of voters if not provided (like with Misskey)
1508 if (empty($question['voters']) && !$question['multiple']) {
1509 $question['voters'] = $voters;
1516 * Fetch the original source or content with the "language" Markdown or HTML
1518 * @param array $object
1519 * @param array $object_data
1522 * @throws \Exception
1524 private static function getSource($object, $object_data)
1526 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1527 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1528 if (!empty($object_data['source'])) {
1529 return $object_data;
1532 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1533 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1534 if (!empty($object_data['source'])) {
1535 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1536 return $object_data;
1539 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1540 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1541 if (!empty($object_data['source'])) {
1542 $object_data['source'] = HTML::toBBCode($object_data['source']);
1543 return $object_data;
1546 return $object_data;
1550 * Extracts a potential alternate URL from a list of additional URL elements
1552 * @param array $urls
1555 private static function extractAlternateUrl(array $urls): string
1558 foreach ($urls as $key => $url) {
1559 // Not a list but a single URL element
1560 if (!is_numeric($key)) {
1564 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1568 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1573 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1574 if (empty($mediatype)) {
1578 if ($mediatype == 'text/html') {
1579 $alternateUrl = $href;
1583 return $alternateUrl;
1587 * Check if the "as:url" element is an array with multiple links
1588 * This is the case with audio and video posts.
1589 * Then the links are added as attachments
1591 * @param array $urls The object URL list
1592 * @return array an array of attachments
1594 private static function processAttachmentUrls(array $urls): array
1597 foreach ($urls as $key => $url) {
1598 // Not a list but a single URL element
1599 if (!is_numeric($key)) {
1603 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1607 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1612 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1613 if (empty($mediatype)) {
1617 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1619 if ($filetype == 'audio') {
1620 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1621 } elseif ($filetype == 'video') {
1622 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1623 // PeerTube audio-only track
1624 if ($height === 0) {
1628 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1629 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1630 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1631 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1633 // For Torrent links we always store the highest resolution
1634 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1638 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1639 } elseif ($mediatype == 'application/x-mpegURL') {
1640 // PeerTube exception, actual video link is in the tags of this URL element
1641 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1645 return array_values($attachments);
1649 * Fetches data from the object part of an activity
1651 * @param array $object
1654 * @throws \Exception
1656 private static function processObject($object)
1658 if (!JsonLD::fetchElement($object, '@id')) {
1663 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1664 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1665 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1667 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1668 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1669 $object_data['reply-to-id'] = $object_data['id'];
1671 // On activities the "reply to" is the id of the object it refers to
1672 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1673 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1674 if (!empty($object_id)) {
1675 $object_data['reply-to-id'] = $object_id;
1679 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1680 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1681 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1682 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1683 $object_data['reply-to-id'] = $replyToId;
1687 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1688 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1690 if (empty($object_data['updated'])) {
1691 $object_data['updated'] = $object_data['published'];
1694 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1695 $object_data['published'] = $object_data['updated'];
1698 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1699 if (empty($actor)) {
1700 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1703 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1704 $location = JsonLD::fetchElement($location, 'location', '@value');
1706 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1707 // down to HTML and then finally format to plaintext.
1708 $location = Markdown::convert($location);
1709 $location = BBCode::toPlaintext($location);
1712 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1713 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1714 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1715 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1716 $object_data['actor'] = $object_data['author'] = $actor;
1717 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1718 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1719 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1720 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1721 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1722 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1723 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1724 $object_data = self::getSource($object, $object_data);
1725 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1726 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1727 $object_data['location'] = $location;
1728 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1729 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1730 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1731 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1732 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1733 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1734 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1735 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1736 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1737 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1738 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1740 // Special treatment for Hubzilla links
1741 if (is_array($object_data['alternate-url'])) {
1742 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1744 if (!is_string($object_data['alternate-url'])) {
1745 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1749 if (!empty($object_data['alternate-url']) && !Network::isValidHttpUrl($object_data['alternate-url'])) {
1750 $object_data['alternate-url'] = null;
1753 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1754 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1755 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1758 // For page types we expect that the alternate url posts to some page.
1759 // So we add this to the attachments if it differs from the id.
1760 // Currently only Lemmy is using the page type.
1761 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1762 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1763 $object_data['alternate-url'] = null;
1766 if ($object_data['object_type'] == 'as:Question') {
1767 $object_data['question'] = self::processQuestion($object);
1770 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1771 $receivers = $reception_types = [];
1772 foreach ($receiverdata as $key => $data) {
1773 $receivers[$key] = $data['uid'];
1774 $reception_types[$data['uid']] = $data['type'] ?? 0;
1777 $object_data['receiver_urls'] = self::getReceiverURL($object);
1778 $object_data['receiver'] = $receivers;
1779 $object_data['reception_type'] = $reception_types;
1781 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1782 unset($object_data['receiver'][-1]);
1783 unset($object_data['reception_type'][-1]);
1785 // Common object data:
1788 // @context, type, actor, signature, mediaType, duration, replies, icon
1790 // Also missing: (Defined in the standard, but currently unused)
1791 // audience, preview, endTime, startTime, image
1796 // contentMap, announcement_count, announcements, context_id, likes, like_count
1797 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1802 // category, licence, language, commentsEnabled
1805 // views, waitTranscoding, state, support, subtitleLanguage
1806 // likes, dislikes, shares, comments
1808 return $object_data;