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\Strings;
45 * ActivityPub Receiver Protocol class
50 * Check what this is meant to do:
59 const PUBLIC_COLLECTION = 'as:Public';
60 const ACCOUNT_TYPES = ['as:Person', 'as:Organization', 'as:Service', 'as:Group', 'as:Application'];
61 const CONTENT_TYPES = ['as:Note', 'as:Article', 'as:Video', 'as:Image', 'as:Event', 'as:Audio', 'as:Page', 'as:Question'];
62 const ACTIVITY_TYPES = ['as:Like', 'as:Dislike', 'as:Accept', 'as:Reject', 'as:TentativeAccept'];
64 const TARGET_UNKNOWN = 0;
69 const TARGET_FOLLOWER = 5;
70 const TARGET_ANSWER = 6;
71 const TARGET_GLOBAL = 7;
73 const COMPLETION_NONE = 0;
74 const COMPLETION_ANNOUCE = 1;
75 const COMPLETION_RELAY = 2;
76 const COMPLETION_MANUAL = 3;
77 const COMPLETION_AUTO = 4;
80 * Checks incoming message from the inbox
84 * @param integer $uid User ID
87 public static function processInbox($body, $header, $uid)
89 $activity = json_decode($body, true);
90 if (empty($activity)) {
91 Logger::warning('Invalid body.');
95 $ldactivity = JsonLD::compact($activity);
97 $actor = JsonLD::fetchElement($ldactivity, 'as:actor', '@id');
99 $apcontact = APContact::getByURL($actor);
100 if (empty($apcontact)) {
101 Logger::notice('Unable to retrieve AP contact for actor - message is discarded', ['actor' => $actor]);
103 } elseif ($apcontact['type'] == 'Application' && $apcontact['nick'] == 'relay') {
104 self::processRelayPost($ldactivity, $actor);
107 APContact::unmarkForArchival($apcontact);
110 $http_signer = HTTPSignature::getSigner($body, $header);
111 if ($http_signer === false) {
112 Logger::warning('Invalid HTTP signature, message will be discarded.');
114 } elseif (empty($http_signer)) {
115 Logger::info('Signer is a tombstone. The message will be discarded, the signer account is deleted.');
118 Logger::info('Valid HTTP signature', ['signer' => $http_signer]);
121 $signer = [$http_signer];
123 Logger::info('Message for user ' . $uid . ' is from actor ' . $actor);
125 if (LDSignature::isSigned($activity)) {
126 $ld_signer = LDSignature::getSigner($activity);
127 if (empty($ld_signer)) {
128 Logger::info('Invalid JSON-LD signature from ' . $actor);
129 } elseif ($ld_signer != $http_signer) {
130 $signer[] = $ld_signer;
132 if (!empty($ld_signer && ($actor == $http_signer))) {
133 Logger::info('The HTTP and the JSON-LD signature belong to ' . $ld_signer);
134 $trust_source = true;
135 } elseif (!empty($ld_signer)) {
136 Logger::info('JSON-LD signature is signed by ' . $ld_signer);
137 $trust_source = true;
138 } elseif ($actor == $http_signer) {
139 Logger::info('Bad JSON-LD signature, but HTTP signer fits the actor.');
140 $trust_source = true;
142 Logger::info('Invalid JSON-LD signature and the HTTP signer is different.');
143 $trust_source = false;
145 } elseif ($actor == $http_signer) {
146 Logger::info('Trusting post without JSON-LD signature, The actor fits the HTTP signer.');
147 $trust_source = true;
149 Logger::info('No JSON-LD signature, different actor.');
150 $trust_source = false;
153 self::processActivity($ldactivity, $body, $uid, $trust_source, true, $signer);
157 * Process incoming posts from relays
159 * @param array $activity
160 * @param string $actor
163 private static function processRelayPost(array $activity, string $actor)
165 $type = JsonLD::fetchElement($activity, '@type');
167 Logger::info('Empty type', ['activity' => $activity]);
171 if ($type != 'as:Announce') {
172 Logger::info('Not an announcement', ['activity' => $activity]);
176 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
177 if (empty($object_id)) {
178 Logger::info('No object id found', ['activity' => $activity]);
182 $contact = Contact::getByURL($actor);
183 if (empty($contact)) {
184 Logger::info('Relay contact not found', ['actor' => $actor]);
188 if (!in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
189 Logger::notice('Relay is no sharer', ['actor' => $actor]);
193 Logger::info('Got relayed message id', ['id' => $object_id]);
195 $item_id = Item::searchByLink($object_id);
197 Logger::info('Relayed message already exists', ['id' => $object_id, 'item' => $item_id]);
201 $id = Processor::fetchMissingActivity($object_id, [], $actor, self::COMPLETION_RELAY);
203 Logger::notice('Relayed message had not been fetched', ['id' => $object_id]);
207 $item_id = Item::searchByLink($object_id);
209 Logger::info('Relayed message had been fetched and stored', ['id' => $object_id, 'item' => $item_id]);
211 Logger::notice('Relayed message had not been stored', ['id' => $object_id]);
216 * Fetches the object type for a given object id
218 * @param array $activity
219 * @param string $object_id Object ID of the the provided object
220 * @param integer $uid User ID
222 * @return string with object type
223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
224 * @throws \ImagickException
226 private static function fetchObjectType($activity, $object_id, $uid = 0)
228 if (!empty($activity['as:object'])) {
229 $object_type = JsonLD::fetchElement($activity['as:object'], '@type');
230 if (!empty($object_type)) {
235 if (Post::exists(['uri' => $object_id, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT]])) {
236 // We just assume "note" since it doesn't make a difference for the further processing
240 $profile = APContact::getByURL($object_id);
241 if (!empty($profile['type'])) {
242 APContact::unmarkForArchival($profile);
243 return 'as:' . $profile['type'];
246 $data = ActivityPub::fetchContent($object_id, $uid);
248 $object = JsonLD::compact($data);
249 $type = JsonLD::fetchElement($object, '@type');
259 * Prepare the object array
261 * @param array $activity Array with activity data
262 * @param integer $uid User ID
263 * @param boolean $push Message had been pushed to our system
264 * @param boolean $trust_source Do we trust the source?
266 * @return array with object data
267 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
268 * @throws \ImagickException
270 public static function prepareObjectData($activity, $uid, $push, &$trust_source)
272 $id = JsonLD::fetchElement($activity, '@id');
273 if (!empty($id) && !$trust_source) {
274 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
276 $fetched_activity = ActivityPub::fetchContent($id, $fetch_uid);
277 if (!empty($fetched_activity)) {
278 $object = JsonLD::compact($fetched_activity);
279 $fetched_id = JsonLD::fetchElement($object, '@id');
280 if ($fetched_id == $id) {
281 Logger::info('Activity had been fetched successfully', ['id' => $id]);
282 $trust_source = true;
285 Logger::info('Activity id is not equal', ['id' => $id, 'fetched' => $fetched_id]);
288 Logger::info('Activity could not been fetched', ['id' => $id]);
292 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
294 Logger::info('Empty actor', ['activity' => $activity]);
298 $type = JsonLD::fetchElement($activity, '@type');
300 // Fetch all receivers from to, cc, bto and bcc
301 $receiverdata = self::getReceivers($activity, $actor);
302 $receivers = $reception_types = [];
303 foreach ($receiverdata as $key => $data) {
304 $receivers[$key] = $data['uid'];
305 $reception_types[$data['uid']] = $data['type'] ?? self::TARGET_UNKNOWN;
308 $urls = self::getReceiverURL($activity);
310 // When it is a delivery to a personal inbox we add that user to the receivers
312 $additional = [$uid => $uid];
313 $receivers = array_replace($receivers, $additional);
314 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]))) {
315 $reception_types[$uid] = self::TARGET_BCC;
316 $owner = User::getOwnerDataById($uid);
317 if (!empty($owner['url'])) {
318 $urls['as:bcc'][] = $owner['url'];
323 // We possibly need some user to fetch private content,
324 // so we fetch one out of the receivers if no uid is provided.
325 $fetch_uid = $uid ?: self::getBestUserForActivity($activity);
327 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
328 if (empty($object_id)) {
329 Logger::info('No object found');
333 if (!is_string($object_id)) {
334 Logger::info('Invalid object id', ['object' => $object_id]);
338 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
340 // Fetch the activity on Lemmy "Announce" messages (announces of activities)
341 if (($type == 'as:Announce') && in_array($object_type, array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
342 $data = ActivityPub::fetchContent($object_id, $fetch_uid);
344 $type = $object_type;
345 $activity = JsonLD::compact($data);
347 // Some variables need to be refetched since the activity changed
348 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
349 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
350 $object_type = self::fetchObjectType($activity, $object_id, $fetch_uid);
354 // Any activities on account types must not be altered
355 if (in_array($object_type, self::ACCOUNT_TYPES)) {
357 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
358 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
359 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
360 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
361 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
362 $object_data['push'] = $push;
363 } elseif (in_array($type, ['as:Create', 'as:Update', 'as:Announce', 'as:Invite']) || strpos($type, '#emojiReaction')) {
364 // Fetch the content only on activities where this matters
365 // We can receive "#emojiReaction" when fetching content from Hubzilla systems
366 // Always fetch on "Announce"
367 $object_data = self::fetchObject($object_id, $activity['as:object'], $trust_source && ($type != 'as:Announce'), $fetch_uid);
368 if (empty($object_data)) {
369 Logger::info("Object data couldn't be processed");
373 $object_data['object_id'] = $object_id;
375 if ($type == 'as:Announce') {
376 $object_data['push'] = false;
378 $object_data['push'] = $push;
381 // Test if it is an answer to a mail
382 if (DBA::exists('mail', ['uri' => $object_data['reply-to-id']])) {
383 $object_data['directmessage'] = true;
385 $object_data['directmessage'] = JsonLD::fetchElement($activity, 'litepub:directMessage');
387 } elseif (in_array($type, array_merge(self::ACTIVITY_TYPES, ['as:Follow', 'litepub:EmojiReact'])) && in_array($object_type, self::CONTENT_TYPES)) {
388 // Create a mostly empty array out of the activity data (instead of the object).
389 // This way we later don't have to check for the existence of each individual array element.
390 $object_data = self::processObject($activity);
391 $object_data['name'] = $type;
392 $object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
393 $object_data['object_id'] = $object_id;
394 $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
395 $object_data['push'] = $push;
396 } elseif (in_array($type, ['as:Add', 'as:Remove'])) {
398 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
399 $object_data['target_id'] = JsonLD::fetchElement($activity, 'as:target', '@id');
400 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
401 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
402 $object_data['object_content'] = JsonLD::fetchElement($activity['as:object'], 'as:content', '@type');
403 $object_data['push'] = $push;
406 $object_data['id'] = JsonLD::fetchElement($activity, '@id');
407 $object_data['object_id'] = JsonLD::fetchElement($activity, 'as:object', '@id');
408 $object_data['object_actor'] = JsonLD::fetchElement($activity['as:object'], 'as:actor', '@id');
409 $object_data['object_object'] = JsonLD::fetchElement($activity['as:object'], 'as:object');
410 $object_data['object_type'] = JsonLD::fetchElement($activity['as:object'], '@type');
411 $object_data['push'] = $push;
413 // An Undo is done on the object of an object, so we need that type as well
414 if (($type == 'as:Undo') && !empty($object_data['object_object'])) {
415 $object_data['object_object_type'] = self::fetchObjectType([], $object_data['object_object'], $fetch_uid);
419 $object_data = self::addActivityFields($object_data, $activity);
421 if (empty($object_data['object_type'])) {
422 $object_data['object_type'] = $object_type;
425 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
426 if ((empty($object_data['receiver_urls'][$element]) || in_array($element, ['as:bto', 'as:bcc'])) && !empty($urls[$element])) {
427 $object_data['receiver_urls'][$element] = array_unique(array_merge($object_data['receiver_urls'][$element] ?? [], $urls[$element]));
431 $object_data['type'] = $type;
432 $object_data['actor'] = $actor;
433 $object_data['item_receiver'] = $receivers;
434 $object_data['receiver'] = array_replace($object_data['receiver'] ?? [], $receivers);
435 $object_data['reception_type'] = array_replace($object_data['reception_type'] ?? [], $reception_types);
437 $author = $object_data['author'] ?? $actor;
438 if (!empty($author) && !empty($object_data['id'])) {
439 $author_host = parse_url($author, PHP_URL_HOST);
440 $id_host = parse_url($object_data['id'], PHP_URL_HOST);
441 if ($author_host == $id_host) {
442 Logger::info('Valid hosts', ['type' => $type, 'host' => $id_host]);
444 Logger::notice('Differing hosts on author and id', ['type' => $type, 'author' => $author_host, 'id' => $id_host]);
445 $trust_source = false;
449 Logger::info('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id']);
455 * Fetches the first user id from the receiver array
457 * @param array $receivers Array with receivers
458 * @return integer user id;
460 public static function getFirstUserFromReceivers($receivers)
462 foreach ($receivers as $receiver) {
463 if (!empty($receiver)) {
471 * Processes the activity object
473 * @param array $activity Array with activity data
474 * @param string $body The unprocessed body
475 * @param integer $uid User ID
476 * @param boolean $trust_source Do we trust the source?
477 * @param boolean $push Message had been pushed to our system
478 * @param array $signer The signer of the post
481 public static function processActivity($activity, string $body = '', int $uid = null, bool $trust_source = false, bool $push = false, array $signer = [])
483 $type = JsonLD::fetchElement($activity, '@type');
485 Logger::info('Empty type', ['activity' => $activity]);
489 if (!JsonLD::fetchElement($activity, 'as:object', '@id')) {
490 Logger::info('Empty object', ['activity' => $activity]);
494 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id');
496 Logger::info('Empty actor', ['activity' => $activity]);
500 if (is_array($activity['as:object'])) {
501 $attributed_to = JsonLD::fetchElement($activity['as:object'], 'as:attributedTo', '@id');
506 // Test the provided signatures against the actor and "attributedTo"
508 if (!empty($attributed_to) && !empty($actor)) {
509 $trust_source = (in_array($actor, $signer) && in_array($attributed_to, $signer));
511 $trust_source = in_array($actor, $signer);
515 // $trust_source is called by reference and is set to true if the content was retrieved successfully
516 $object_data = self::prepareObjectData($activity, $uid, $push, $trust_source);
517 if (empty($object_data)) {
518 Logger::info('No object data found', ['activity' => $activity]);
522 // Lemmy is announcing activities.
523 // We are changing the announces into regular activities.
524 if (($type == 'as:Announce') && in_array($object_data['type'] ?? '', array_merge(self::ACTIVITY_TYPES, ['as:Delete', 'as:Undo', 'as:Update']))) {
525 $type = $object_data['type'];
528 if (!$trust_source) {
529 Logger::info('Activity trust could not be achieved.', ['id' => $object_data['object_id'], 'type' => $type, 'signer' => $signer, 'actor' => $actor, 'attributedTo' => $attributed_to]);
533 if (!empty($body) && empty($object_data['raw'])) {
534 $object_data['raw'] = $body;
537 // Internal flag for thread completion. See Processor.php
538 if (!empty($activity['thread-completion'])) {
539 $object_data['thread-completion'] = $activity['thread-completion'];
542 if (!empty($activity['completion-mode'])) {
543 $object_data['completion-mode'] = $activity['completion-mode'];
546 if (!empty($activity['thread-children-type'])) {
547 $object_data['thread-children-type'] = $activity['thread-children-type'];
550 // Internal flag for posts that arrived via relay
551 if (!empty($activity['from-relay'])) {
552 $object_data['from-relay'] = $activity['from-relay'];
557 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
558 $item = ActivityPub\Processor::createItem($object_data);
559 ActivityPub\Processor::postItem($object_data, $item);
560 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
561 // Unhandled Peertube activity
563 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
568 if (in_array($object_data['object_type'], ['as:Event'])) {
569 $item = ActivityPub\Processor::createItem($object_data);
570 ActivityPub\Processor::postItem($object_data, $item);
572 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
577 if ($object_data['object_type'] == 'as:tag') {
578 ActivityPub\Processor::addTag($object_data);
579 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
580 // Seems to be used by Mastodon to announce that a post is pinned
581 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
582 } elseif ($object_data['object_type'] == '') {
583 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
585 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
590 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
591 $object_data['thread-completion'] = Contact::getIdForURL($actor);
592 $object_data['completion-mode'] = self::COMPLETION_ANNOUCE;
594 $item = ActivityPub\Processor::createItem($object_data);
599 $item['post-reason'] = Item::PR_ANNOUNCEMENT;
600 ActivityPub\Processor::postItem($object_data, $item);
602 $announce_object_data = self::processObject($activity);
603 $announce_object_data['name'] = $type;
604 $announce_object_data['author'] = JsonLD::fetchElement($activity, 'as:actor', '@id');
605 $announce_object_data['object_id'] = $object_data['object_id'];
606 $announce_object_data['object_type'] = $object_data['object_type'];
607 $announce_object_data['push'] = $push;
610 $announce_object_data['raw'] = $body;
613 ActivityPub\Processor::createActivity($announce_object_data, Activity::ANNOUNCE);
615 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
620 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
621 ActivityPub\Processor::createActivity($object_data, Activity::LIKE);
622 } elseif ($object_data['object_type'] == '') {
623 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
625 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
630 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
631 ActivityPub\Processor::createActivity($object_data, Activity::DISLIKE);
632 } elseif ($object_data['object_type'] == '') {
633 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
635 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
639 case 'as:TentativeAccept':
640 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
641 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDMAYBE);
643 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
648 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
649 ActivityPub\Processor::updateItem($object_data);
650 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
651 ActivityPub\Processor::updatePerson($object_data);
652 } elseif (in_array($object_data['object_type'], ['pt:CacheFile'])) {
653 // Unhandled Peertube activity
655 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
660 if (in_array($object_data['object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
661 ActivityPub\Processor::deleteItem($object_data);
662 } elseif (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
663 ActivityPub\Processor::deletePerson($object_data);
664 } elseif ($object_data['object_type'] == '') {
665 // The object type couldn't be determined. Most likely we don't have it here. We ignore this activity.
667 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
672 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
673 // Used by Mastodon to announce that the sender has blocked the account
674 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
676 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
681 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
682 // Seems to be used by Mastodon to remove the pinned status of a post
683 self::storeUnhandledActivity(false, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
684 } elseif ($object_data['object_type'] == '') {
685 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
687 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
692 if (in_array($object_data['object_type'], self::ACCOUNT_TYPES)) {
693 ActivityPub\Processor::followUser($object_data);
694 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
695 $object_data['reply-to-id'] = $object_data['object_id'];
696 ActivityPub\Processor::createActivity($object_data, Activity::FOLLOW);
698 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
703 if ($object_data['object_type'] == 'as:Follow') {
704 ActivityPub\Processor::acceptFollowUser($object_data);
705 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
706 ActivityPub\Processor::createActivity($object_data, Activity::ATTEND);
708 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
713 if ($object_data['object_type'] == 'as:Follow') {
714 ActivityPub\Processor::rejectFollowUser($object_data);
715 } elseif (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
716 ActivityPub\Processor::createActivity($object_data, Activity::ATTENDNO);
718 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
723 if (($object_data['object_type'] == 'as:Follow') &&
724 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
725 ActivityPub\Processor::undoFollowUser($object_data);
726 } elseif (($object_data['object_type'] == 'as:Follow') &&
727 in_array($object_data['object_object_type'], self::CONTENT_TYPES)) {
728 ActivityPub\Processor::undoActivity($object_data);
729 } elseif (($object_data['object_type'] == 'as:Accept') &&
730 in_array($object_data['object_object_type'], self::ACCOUNT_TYPES)) {
731 ActivityPub\Processor::rejectFollowUser($object_data);
732 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce'])) &&
733 in_array($object_data['object_object_type'], array_merge(['as:Tombstone'], self::CONTENT_TYPES))) {
734 ActivityPub\Processor::undoActivity($object_data);
735 } elseif (in_array($object_data['object_type'], array_merge(self::ACTIVITY_TYPES, ['as:Announce', 'as:Create', ''])) &&
736 empty($object_data['object_object_type'])) {
737 // We cannot detect the target object. So we can ignore it.
738 } elseif (in_array($object_data['object_type'], ['as:Create']) &&
739 in_array($object_data['object_object_type'], ['pt:CacheFile'])) {
740 // Unhandled Peertube activity
742 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
747 if (in_array($object_data['object_type'], ['as:Note', 'as:Video'])) {
748 // Unhandled Peertube activity
750 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
754 case 'litepub:EmojiReact':
755 if (in_array($object_data['object_type'], self::CONTENT_TYPES)) {
756 ActivityPub\Processor::createActivity($object_data, Activity::EMOJIREACT);
757 } elseif ($object_data['object_type'] == '') {
758 // The object type couldn't be determined. We don't have it and we can't fetch it. We ignore this activity.
760 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
765 Logger::info('Unknown activity: ' . $type . ' ' . $object_data['object_type']);
766 self::storeUnhandledActivity(true, $type, $object_data, $activity, $body, $uid, $trust_source, $push, $signer);
772 * Stores unhandled or unknown Activities as a file
774 * @param boolean $unknown "true" if the activity is unknown, "false" if it is unhandled
775 * @param string $type Activity type
776 * @param array $object_data Preprocessed array that is generated out of the received activity
777 * @param array $activity Array with activity data
778 * @param string $body The unprocessed body
779 * @param integer $uid User ID
780 * @param boolean $trust_source Do we trust the source?
781 * @param boolean $push Message had been pushed to our system
782 * @param array $signer The signer of the post
785 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 = [])
787 if (!DI::config()->get('debug', 'ap_log_unknown')) {
791 $file = ($unknown ? 'unknown-' : 'unhandled-') . str_replace(':', '-', $type) . '-';
793 if (!empty($object_data['object_type'])) {
794 $file .= str_replace(':', '-', $object_data['object_type']) . '-';
797 if (!empty($object_data['object_object_type'])) {
798 $file .= str_replace(':', '-', $object_data['object_object_type']) . '-';
801 $tempfile = tempnam(System::getTempPath(), $file);
802 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));
803 Logger::notice('Unknown activity stored', ['type' => $type, 'object_type' => $object_data['object_type'], $object_data['object_object_type'] ?? '', 'file' => $tempfile]);
807 * Fetch a user id from an activity array
809 * @param array $activity
810 * @param string $actor
812 * @return int user id
814 public static function getBestUserForActivity(array $activity)
817 $actor = JsonLD::fetchElement($activity, 'as:actor', '@id') ?? '';
819 $receivers = self::getReceivers($activity, $actor);
820 foreach ($receivers as $receiver) {
821 if ($receiver['type'] == self::TARGET_GLOBAL) {
824 if (empty($uid) || ($receiver['type'] == self::TARGET_TO)) {
825 $uid = $receiver['uid'];
829 // When we haven't found any user yet, we just chose a user who most likely could have access to the content
831 $contact = Contact::selectFirst(['uid'], ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND]]);
832 if (!empty($contact['uid'])) {
833 $uid = $contact['uid'];
840 public static function getReceiverURL($activity)
844 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
845 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
846 if (empty($receiver_list)) {
850 foreach ($receiver_list as $receiver) {
851 if ($receiver == self::PUBLIC_COLLECTION) {
852 $receiver = ActivityPub::PUBLIC_COLLECTION;
854 $urls[$element][] = $receiver;
862 * Fetch the receiver list from an activity array
864 * @param array $activity
865 * @param string $actor
867 * @param boolean $fetch_unlisted
869 * @return array with receivers (user id)
872 private static function getReceivers($activity, $actor, $tags = [], $fetch_unlisted = false)
874 $reply = $receivers = [];
876 // When it is an answer, we inherite the receivers from the parent
877 $replyto = JsonLD::fetchElement($activity, 'as:inReplyTo', '@id');
878 if (!empty($replyto)) {
881 // Fix possibly wrong item URI (could be an answer to a plink uri)
882 $fixedReplyTo = Item::getURIByLink($replyto);
883 if (!empty($fixedReplyTo)) {
884 $reply[] = $fixedReplyTo;
888 // Fetch all posts that refer to the object id
889 $object_id = JsonLD::fetchElement($activity, 'as:object', '@id');
890 if (!empty($object_id)) {
891 $reply[] = $object_id;
894 if (!empty($reply)) {
895 $parents = Post::select(['uid'], ['uri' => $reply]);
896 while ($parent = Post::fetch($parents)) {
897 $receivers[$parent['uid']] = ['uid' => $parent['uid'], 'type' => self::TARGET_ANSWER];
899 DBA::close($parents);
902 if (!empty($actor)) {
903 $profile = APContact::getByURL($actor);
904 $followers = $profile['followers'] ?? '';
905 $is_forum = ($actor['type'] ?? '') == 'Group';
906 Logger::info('Got actor and followers', ['actor' => $actor, 'followers' => $followers]);
908 Logger::info('Empty actor', ['activity' => $activity]);
913 // We have to prevent false follower assumptions upon thread completions
914 $follower_target = empty($activity['thread-completion']) ? self::TARGET_FOLLOWER : self::TARGET_UNKNOWN;
916 foreach (['as:to', 'as:cc', 'as:bto', 'as:bcc'] as $element) {
917 $receiver_list = JsonLD::fetchElementArray($activity, $element, '@id');
918 if (empty($receiver_list)) {
922 foreach ($receiver_list as $receiver) {
923 if ($receiver == self::PUBLIC_COLLECTION) {
924 $receivers[0] = ['uid' => 0, 'type' => self::TARGET_GLOBAL];
927 // Add receiver "-1" for unlisted posts
928 if ($fetch_unlisted && ($receiver == self::PUBLIC_COLLECTION) && ($element == 'as:cc')) {
929 $receivers[-1] = ['uid' => -1, 'type' => self::TARGET_GLOBAL];
932 // Fetch the receivers for the public and the followers collection
933 if ((($receiver == $followers) || (($receiver == self::PUBLIC_COLLECTION) && !$is_forum)) && !empty($actor)) {
934 $receivers = self::getReceiverForActor($actor, $tags, $receivers, $follower_target);
938 // Fetching all directly addressed receivers
939 $condition = ['self' => true, 'nurl' => Strings::normaliseLink($receiver)];
940 $contact = DBA::selectFirst('contact', ['uid', 'contact-type'], $condition);
941 if (!DBA::isResult($contact)) {
945 // Check if the potential receiver is following the actor
946 // Exception: The receiver is targetted via "to" or this is a comment
947 if ((($element != 'as:to') && empty($replyto)) || ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
948 $networks = Protocol::FEDERATED;
949 $condition = ['nurl' => Strings::normaliseLink($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
950 'network' => $networks, 'archive' => false, 'pending' => false, 'uid' => $contact['uid']];
952 // Forum posts are only accepted from forum contacts
953 if ($contact['contact-type'] == Contact::TYPE_COMMUNITY) {
954 $condition['rel'] = [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER];
957 if (!DBA::exists('contact', $condition)) {
962 $type = $receivers[$contact['uid']]['type'] ?? self::TARGET_UNKNOWN;
963 if (in_array($type, [self::TARGET_UNKNOWN, self::TARGET_FOLLOWER, self::TARGET_ANSWER, self::TARGET_GLOBAL])) {
966 $type = self::TARGET_TO;
969 $type = self::TARGET_CC;
972 $type = self::TARGET_BTO;
975 $type = self::TARGET_BCC;
979 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $type];
984 self::switchContacts($receivers, $actor);
990 * Fetch the receiver list of a given actor
992 * @param string $actor
994 * @param array $receivers
995 * @param integer $target_type
997 * @return array with receivers (user id)
1000 private static function getReceiverForActor($actor, $tags, $receivers, $target_type)
1002 $basecondition = ['rel' => [Contact::SHARING, Contact::FRIEND, Contact::FOLLOWER],
1003 'network' => Protocol::FEDERATED, 'archive' => false, 'pending' => false];
1005 $condition = DBA::mergeConditions($basecondition, ["`nurl` = ? AND `uid` != ?", Strings::normaliseLink($actor), 0]);
1006 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1007 while ($contact = DBA::fetch($contacts)) {
1008 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1009 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1012 DBA::close($contacts);
1014 // The queries are split because of performance issues
1015 $condition = DBA::mergeConditions($basecondition, ["`alias` IN (?, ?) AND `uid` != ?", Strings::normaliseLink($actor), $actor, 0]);
1016 $contacts = DBA::select('contact', ['uid', 'rel'], $condition);
1017 while ($contact = DBA::fetch($contacts)) {
1018 if (empty($receivers[$contact['uid']]) && self::isValidReceiverForActor($contact, $tags)) {
1019 $receivers[$contact['uid']] = ['uid' => $contact['uid'], 'type' => $target_type];
1022 DBA::close($contacts);
1027 * Tests if the contact is a valid receiver for this actor
1029 * @param array $contact
1030 * @param string $actor
1031 * @param array $tags
1033 * @return bool with receivers (user id)
1034 * @throws \Exception
1036 private static function isValidReceiverForActor($contact, $tags)
1038 // Are we following the contact? Then this is a valid receiver
1039 if (in_array($contact['rel'], [Contact::SHARING, Contact::FRIEND])) {
1043 // When the possible receiver isn't a community, then it is no valid receiver
1044 $owner = User::getOwnerDataById($contact['uid']);
1045 if (empty($owner) || ($owner['contact-type'] != Contact::TYPE_COMMUNITY)) {
1049 // Is the community account tagged?
1050 foreach ($tags as $tag) {
1051 if ($tag['type'] != 'Mention') {
1055 if (Strings::compareLink($tag['href'], $owner['url'])) {
1064 * Switches existing contacts to ActivityPub
1066 * @param integer $cid Contact ID
1067 * @param integer $uid User ID
1068 * @param string $url Profile URL
1069 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1070 * @throws \ImagickException
1072 public static function switchContact($cid, $uid, $url)
1074 if (DBA::exists('contact', ['id' => $cid, 'network' => Protocol::ACTIVITYPUB])) {
1075 Logger::info('Contact is already ActivityPub', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1079 if (Contact::updateFromProbe($cid)) {
1080 Logger::info('Update was successful', ['id' => $cid, 'uid' => $uid, 'url' => $url]);
1083 // Send a new follow request to be sure that the connection still exists
1084 if (($uid != 0) && DBA::exists('contact', ['id' => $cid, 'rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB])) {
1085 Logger::info('Contact had been switched to ActivityPub. Sending a new follow request.', ['uid' => $uid, 'url' => $url]);
1086 ActivityPub\Transmitter::sendActivity('Follow', $url, $uid);
1095 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1096 * @throws \ImagickException
1098 private static function switchContacts($receivers, $actor)
1100 if (empty($actor)) {
1104 foreach ($receivers as $receiver) {
1105 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'nurl' => Strings::normaliseLink($actor)]);
1106 if (DBA::isResult($contact)) {
1107 self::switchContact($contact['id'], $receiver['uid'], $actor);
1110 $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver['uid'], 'network' => Protocol::OSTATUS, 'alias' => [Strings::normaliseLink($actor), $actor]]);
1111 if (DBA::isResult($contact)) {
1112 self::switchContact($contact['id'], $receiver['uid'], $actor);
1120 * @param $object_data
1121 * @param array $activity
1125 private static function addActivityFields($object_data, $activity)
1127 if (!empty($activity['published']) && empty($object_data['published'])) {
1128 $object_data['published'] = JsonLD::fetchElement($activity, 'as:published', '@value');
1131 if (!empty($activity['diaspora:guid']) && empty($object_data['diaspora:guid'])) {
1132 $object_data['diaspora:guid'] = JsonLD::fetchElement($activity, 'diaspora:guid', '@value');
1135 $object_data['service'] = JsonLD::fetchElement($activity, 'as:instrument', 'as:name', '@type', 'as:Service');
1136 $object_data['service'] = JsonLD::fetchElement($object_data, 'service', '@value');
1138 if (!empty($object_data['object_id'])) {
1139 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1140 $objectId = Item::getURIByLink($object_data['object_id']);
1141 if (!empty($objectId) && ($object_data['object_id'] != $objectId)) {
1142 Logger::notice('Fix wrong object-id', ['received' => $object_data['object_id'], 'correct' => $objectId]);
1143 $object_data['object_id'] = $objectId;
1147 return $object_data;
1151 * Fetches the object data from external ressources if needed
1153 * @param string $object_id Object ID of the the provided object
1154 * @param array $object The provided object array
1155 * @param boolean $trust_source Do we trust the provided object?
1156 * @param integer $uid User ID for the signature that we use to fetch data
1158 * @return array|false with trusted and valid object data
1159 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1160 * @throws \ImagickException
1162 private static function fetchObject(string $object_id, array $object = [], bool $trust_source = false, int $uid = 0)
1164 // By fetching the type we check if the object is complete.
1165 $type = JsonLD::fetchElement($object, '@type');
1167 if (!$trust_source || empty($type)) {
1168 $data = ActivityPub::fetchContent($object_id, $uid);
1169 if (!empty($data)) {
1170 $object = JsonLD::compact($data);
1171 Logger::info('Fetched content for ' . $object_id);
1173 Logger::info('Empty content for ' . $object_id . ', check if content is available locally.');
1175 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri' => $object_id]);
1176 if (!DBA::isResult($item)) {
1177 Logger::info('Object with url ' . $object_id . ' was not found locally.');
1180 Logger::info('Using already stored item for url ' . $object_id);
1181 $data = ActivityPub\Transmitter::createNote($item);
1182 $object = JsonLD::compact($data);
1185 $id = JsonLD::fetchElement($object, '@id');
1187 Logger::info('Empty id');
1191 if ($id != $object_id) {
1192 Logger::info('Fetched id differs from provided id', ['provided' => $object_id, 'fetched' => $id]);
1196 Logger::info('Using original object for url ' . $object_id);
1199 $type = JsonLD::fetchElement($object, '@type');
1201 Logger::info('Empty type');
1205 // Lemmy is resharing "create" activities instead of content
1206 // We fetch the content from the activity.
1207 if (in_array($type, ['as:Create'])) {
1208 $object = $object['as:object'];
1209 $type = JsonLD::fetchElement($object, '@type');
1211 Logger::info('Empty type');
1214 $object_data = self::processObject($object);
1217 // We currently don't handle 'pt:CacheFile', but with this step we avoid logging
1218 if (in_array($type, self::CONTENT_TYPES) || ($type == 'pt:CacheFile')) {
1219 $object_data = self::processObject($object);
1221 if (!empty($data)) {
1222 $object_data['raw'] = json_encode($data);
1224 return $object_data;
1227 if ($type == 'as:Announce') {
1228 $object_id = JsonLD::fetchElement($object, 'object', '@id');
1229 if (empty($object_id) || !is_string($object_id)) {
1232 return self::fetchObject($object_id, [], false, $uid);
1235 Logger::info('Unhandled object type: ' . $type);
1240 * Converts the language element (Used by Peertube)
1242 * @param array $languages
1243 * @return array Languages
1245 public static function processLanguages(array $languages)
1247 if (empty($languages)) {
1251 $language_list = [];
1253 foreach ($languages as $language) {
1254 if (!empty($language['_:identifier']) && !empty($language['as:name'])) {
1255 $language_list[$language['_:identifier']] = $language['as:name'];
1258 return $language_list;
1262 * Convert tags from JSON-LD format into a simplified format
1264 * @param array $tags Tags in JSON-LD format
1266 * @return array with tags in a simplified format
1268 public static function processTags(array $tags)
1272 foreach ($tags as $tag) {
1277 $element = ['type' => str_replace('as:', '', JsonLD::fetchElement($tag, '@type')),
1278 'href' => JsonLD::fetchElement($tag, 'as:href', '@id'),
1279 'name' => JsonLD::fetchElement($tag, 'as:name', '@value')];
1281 if (empty($element['type'])) {
1285 if (empty($element['href'])) {
1286 $element['href'] = $element['name'];
1289 $taglist[] = $element;
1295 * Convert emojis from JSON-LD format into a simplified format
1297 * @param array $emojis
1298 * @return array with emojis in a simplified format
1300 private static function processEmojis(array $emojis)
1304 foreach ($emojis as $emoji) {
1305 if (empty($emoji) || (JsonLD::fetchElement($emoji, '@type') != 'toot:Emoji') || empty($emoji['as:icon'])) {
1309 $url = JsonLD::fetchElement($emoji['as:icon'], 'as:url', '@id');
1310 $element = ['name' => JsonLD::fetchElement($emoji, 'as:name', '@value'),
1313 $emojilist[] = $element;
1320 * Convert attachments from JSON-LD format into a simplified format
1322 * @param array $attachments Attachments in JSON-LD format
1324 * @return array Attachments in a simplified format
1326 private static function processAttachments(array $attachments)
1330 // Removes empty values
1331 $attachments = array_filter($attachments);
1333 foreach ($attachments as $attachment) {
1334 switch (JsonLD::fetchElement($attachment, '@type')) {
1339 $urls = JsonLD::fetchElementArray($attachment, 'as:url');
1340 foreach ($urls as $url) {
1341 // Single scalar URL case
1342 if (is_string($url)) {
1347 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1348 $mediaType = JsonLD::fetchElement($url, 'as:mediaType', '@value');
1349 if (Strings::startsWith($mediaType, 'image')) {
1358 'title' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1359 'desc' => JsonLD::fetchElement($attachment, 'as:summary', '@value'),
1361 'image' => $pageImage,
1365 $mediaType = JsonLD::fetchElement($attachment, 'as:mediaType', '@value');
1366 $imageFullUrl = JsonLD::fetchElement($attachment, 'as:url', '@id');
1367 $imagePreviewUrl = null;
1369 if (!$imageFullUrl && ($urls = JsonLD::fetchElementArray($attachment, 'as:url'))) {
1370 $imageVariants = [];
1371 $previewVariants = [];
1372 foreach ($urls as $url) {
1373 // Scalar URL, no discrimination possible
1374 if (is_string($url)) {
1375 $imageFullUrl = $url;
1379 // Not sure what to do with a different Link media type than the base Image, we skip
1380 if ($mediaType != JsonLD::fetchElement($url, 'as:mediaType', '@value')) {
1384 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1386 // Default URL choice if no discriminating width is provided
1387 $imageFullUrl = $href ?? $imageFullUrl;
1389 $width = intval(JsonLD::fetchElement($url, 'as:width', '@value') ?? 1);
1391 if ($href && $width) {
1392 $imageVariants[$width] = $href;
1393 // 632 is the ideal width for full screen frio posts, we compute the absolute distance to it
1394 $previewVariants[abs(632 - $width)] = $href;
1398 if ($imageVariants) {
1399 // Taking the maximum size image
1400 ksort($imageVariants);
1401 $imageFullUrl = array_pop($imageVariants);
1403 // Taking the minimum number distance to the target distance
1404 ksort($previewVariants);
1405 $imagePreviewUrl = array_shift($previewVariants);
1408 unset($imageVariants);
1409 unset($previewVariants);
1413 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1414 'mediaType' => $mediaType,
1415 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1416 'url' => $imageFullUrl,
1417 'image' => $imagePreviewUrl !== $imageFullUrl ? $imagePreviewUrl : null,
1422 'type' => str_replace('as:', '', JsonLD::fetchElement($attachment, '@type')),
1423 'mediaType' => JsonLD::fetchElement($attachment, 'as:mediaType', '@value'),
1424 'name' => JsonLD::fetchElement($attachment, 'as:name', '@value'),
1425 'url' => JsonLD::fetchElement($attachment, 'as:url', '@id'),
1426 'height' => JsonLD::fetchElement($attachment, 'as:height', '@value'),
1427 'width' => JsonLD::fetchElement($attachment, 'as:width', '@value'),
1428 'image' => JsonLD::fetchElement($attachment, 'as:image', '@id')
1437 * Fetch the original source or content with the "language" Markdown or HTML
1439 * @param array $object
1440 * @param array $object_data
1443 * @throws \Exception
1445 private static function getSource($object, $object_data)
1447 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/bbcode');
1448 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1449 if (!empty($object_data['source'])) {
1450 return $object_data;
1453 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/markdown');
1454 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1455 if (!empty($object_data['source'])) {
1456 $object_data['source'] = Markdown::toBBCode($object_data['source']);
1457 return $object_data;
1460 $object_data['source'] = JsonLD::fetchElement($object, 'as:source', 'as:content', 'as:mediaType', 'text/html');
1461 $object_data['source'] = JsonLD::fetchElement($object_data, 'source', '@value');
1462 if (!empty($object_data['source'])) {
1463 $object_data['source'] = HTML::toBBCode($object_data['source']);
1464 return $object_data;
1467 return $object_data;
1471 * Extracts a potential alternate URL from a list of additional URL elements
1473 * @param array $urls
1476 private static function extractAlternateUrl(array $urls): string
1479 foreach ($urls as $key => $url) {
1480 // Not a list but a single URL element
1481 if (!is_numeric($key)) {
1485 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1489 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1494 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1495 if (empty($mediatype)) {
1499 if ($mediatype == 'text/html') {
1500 $alternateUrl = $href;
1504 return $alternateUrl;
1508 * Check if the "as:url" element is an array with multiple links
1509 * This is the case with audio and video posts.
1510 * Then the links are added as attachments
1512 * @param array $urls The object URL list
1513 * @return array an array of attachments
1515 private static function processAttachmentUrls(array $urls): array
1518 foreach ($urls as $key => $url) {
1519 // Not a list but a single URL element
1520 if (!is_numeric($key)) {
1524 if (empty($url['@type']) || ($url['@type'] != 'as:Link')) {
1528 $href = JsonLD::fetchElement($url, 'as:href', '@id');
1533 $mediatype = JsonLD::fetchElement($url, 'as:mediaType');
1534 if (empty($mediatype)) {
1538 $filetype = strtolower(substr($mediatype, 0, strpos($mediatype, '/')));
1540 if ($filetype == 'audio') {
1541 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => null, 'size' => null, 'name' => ''];
1542 } elseif ($filetype == 'video') {
1543 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1544 // PeerTube audio-only track
1545 if ($height === 0) {
1549 $size = (int)JsonLD::fetchElement($url, 'pt:size', '@value');
1550 $attachments[] = ['type' => $filetype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => $size, 'name' => ''];
1551 } elseif (in_array($mediatype, ['application/x-bittorrent', 'application/x-bittorrent;x-scheme-handler/magnet'])) {
1552 $height = (int)JsonLD::fetchElement($url, 'as:height', '@value');
1554 // For Torrent links we always store the highest resolution
1555 if (!empty($attachments[$mediatype]['height']) && ($height < $attachments[$mediatype]['height'])) {
1559 $attachments[$mediatype] = ['type' => $mediatype, 'mediaType' => $mediatype, 'url' => $href, 'height' => $height, 'size' => null, 'name' => ''];
1560 } elseif ($mediatype == 'application/x-mpegURL') {
1561 // PeerTube exception, actual video link is in the tags of this URL element
1562 $attachments = array_merge($attachments, self::processAttachmentUrls($url['as:tag']));
1566 return array_values($attachments);
1570 * Fetches data from the object part of an activity
1572 * @param array $object
1575 * @throws \Exception
1577 private static function processObject($object)
1579 if (!JsonLD::fetchElement($object, '@id')) {
1584 $object_data['object_type'] = JsonLD::fetchElement($object, '@type');
1585 $object_data['id'] = JsonLD::fetchElement($object, '@id');
1586 $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'as:inReplyTo', '@id');
1588 // An empty "id" field is translated to "./" by the compactor, so we have to check for this content
1589 if (empty($object_data['reply-to-id']) || ($object_data['reply-to-id'] == './')) {
1590 $object_data['reply-to-id'] = $object_data['id'];
1592 // On activities the "reply to" is the id of the object it refers to
1593 if (in_array($object_data['object_type'], self::ACTIVITY_TYPES)) {
1594 $object_id = JsonLD::fetchElement($object, 'as:object', '@id');
1595 if (!empty($object_id)) {
1596 $object_data['reply-to-id'] = $object_id;
1600 // Some systems (e.g. GNU Social) don't reply to the "id" field but the "uri" field.
1601 $replyToId = Item::getURIByLink($object_data['reply-to-id']);
1602 if (!empty($replyToId) && ($object_data['reply-to-id'] != $replyToId)) {
1603 Logger::notice('Fix wrong reply-to', ['received' => $object_data['reply-to-id'], 'correct' => $replyToId]);
1604 $object_data['reply-to-id'] = $replyToId;
1608 $object_data['published'] = JsonLD::fetchElement($object, 'as:published', '@value');
1609 $object_data['updated'] = JsonLD::fetchElement($object, 'as:updated', '@value');
1611 if (empty($object_data['updated'])) {
1612 $object_data['updated'] = $object_data['published'];
1615 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1616 $object_data['published'] = $object_data['updated'];
1619 $actor = JsonLD::fetchElement($object, 'as:attributedTo', '@id');
1620 if (empty($actor)) {
1621 $actor = JsonLD::fetchElement($object, 'as:actor', '@id');
1624 $location = JsonLD::fetchElement($object, 'as:location', 'as:name', '@type', 'as:Place');
1625 $location = JsonLD::fetchElement($location, 'location', '@value');
1627 // Some AP software allow formatted text in post location, so we run all the text converters we have to boil
1628 // down to HTML and then finally format to plaintext.
1629 $location = Markdown::convert($location);
1630 $location = BBCode::toPlaintext($location);
1633 $object_data['sc:identifier'] = JsonLD::fetchElement($object, 'sc:identifier', '@value');
1634 $object_data['diaspora:guid'] = JsonLD::fetchElement($object, 'diaspora:guid', '@value');
1635 $object_data['diaspora:comment'] = JsonLD::fetchElement($object, 'diaspora:comment', '@value');
1636 $object_data['diaspora:like'] = JsonLD::fetchElement($object, 'diaspora:like', '@value');
1637 $object_data['actor'] = $object_data['author'] = $actor;
1638 $object_data['context'] = JsonLD::fetchElement($object, 'as:context', '@id');
1639 $object_data['conversation'] = JsonLD::fetchElement($object, 'ostatus:conversation', '@id');
1640 $object_data['sensitive'] = JsonLD::fetchElement($object, 'as:sensitive');
1641 $object_data['name'] = JsonLD::fetchElement($object, 'as:name', '@value');
1642 $object_data['summary'] = JsonLD::fetchElement($object, 'as:summary', '@value');
1643 $object_data['content'] = JsonLD::fetchElement($object, 'as:content', '@value');
1644 $object_data['mediatype'] = JsonLD::fetchElement($object, 'as:mediaType', '@value');
1645 $object_data = self::getSource($object, $object_data);
1646 $object_data['start-time'] = JsonLD::fetchElement($object, 'as:startTime', '@value');
1647 $object_data['end-time'] = JsonLD::fetchElement($object, 'as:endTime', '@value');
1648 $object_data['location'] = $location;
1649 $object_data['latitude'] = JsonLD::fetchElement($object, 'as:location', 'as:latitude', '@type', 'as:Place');
1650 $object_data['latitude'] = JsonLD::fetchElement($object_data, 'latitude', '@value');
1651 $object_data['longitude'] = JsonLD::fetchElement($object, 'as:location', 'as:longitude', '@type', 'as:Place');
1652 $object_data['longitude'] = JsonLD::fetchElement($object_data, 'longitude', '@value');
1653 $object_data['attachments'] = self::processAttachments(JsonLD::fetchElementArray($object, 'as:attachment') ?? []);
1654 $object_data['tags'] = self::processTags(JsonLD::fetchElementArray($object, 'as:tag') ?? []);
1655 $object_data['emojis'] = self::processEmojis(JsonLD::fetchElementArray($object, 'as:tag', null, '@type', 'toot:Emoji') ?? []);
1656 $object_data['languages'] = self::processLanguages(JsonLD::fetchElementArray($object, 'sc:inLanguage') ?? []);
1657 $object_data['generator'] = JsonLD::fetchElement($object, 'as:generator', 'as:name', '@type', 'as:Application');
1658 $object_data['generator'] = JsonLD::fetchElement($object_data, 'generator', '@value');
1659 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'as:url', '@id');
1661 // Special treatment for Hubzilla links
1662 if (is_array($object_data['alternate-url'])) {
1663 $object_data['alternate-url'] = JsonLD::fetchElement($object_data['alternate-url'], 'as:href', '@id');
1665 if (!is_string($object_data['alternate-url'])) {
1666 $object_data['alternate-url'] = JsonLD::fetchElement($object['as:url'], 'as:href', '@id');
1670 if (in_array($object_data['object_type'], ['as:Audio', 'as:Video'])) {
1671 $object_data['alternate-url'] = self::extractAlternateUrl($object['as:url'] ?? []) ?: $object_data['alternate-url'];
1672 $object_data['attachments'] = array_merge($object_data['attachments'], self::processAttachmentUrls($object['as:url'] ?? []));
1675 // For page types we expect that the alternate url posts to some page.
1676 // So we add this to the attachments if it differs from the id.
1677 // Currently only Lemmy is using the page type.
1678 if (($object_data['object_type'] == 'as:Page') && !empty($object_data['alternate-url']) && !Strings::compareLink($object_data['alternate-url'], $object_data['id'])) {
1679 $object_data['attachments'][] = ['url' => $object_data['alternate-url']];
1680 $object_data['alternate-url'] = null;
1683 $receiverdata = self::getReceivers($object, $object_data['actor'], $object_data['tags'], true);
1684 $receivers = $reception_types = [];
1685 foreach ($receiverdata as $key => $data) {
1686 $receivers[$key] = $data['uid'];
1687 $reception_types[$data['uid']] = $data['type'] ?? 0;
1690 $object_data['receiver_urls'] = self::getReceiverURL($object);
1691 $object_data['receiver'] = $receivers;
1692 $object_data['reception_type'] = $reception_types;
1694 $object_data['unlisted'] = in_array(-1, $object_data['receiver']);
1695 unset($object_data['receiver'][-1]);
1696 unset($object_data['reception_type'][-1]);
1698 // Common object data:
1701 // @context, type, actor, signature, mediaType, duration, replies, icon
1703 // Also missing: (Defined in the standard, but currently unused)
1704 // audience, preview, endTime, startTime, image
1709 // contentMap, announcement_count, announcements, context_id, likes, like_count
1710 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1715 // category, licence, language, commentsEnabled
1718 // views, waitTranscoding, state, support, subtitleLanguage
1719 // likes, dislikes, shares, comments
1721 return $object_data;