*/
const SKIP_TAGS = array( 'BR', 'CITE', 'SOURCE' );
/**
* HTML void elements that have no closing tag.
*
* @var array
*/
const VOID_TAGS = array( 'AREA', 'BASE', 'BR', 'COL', 'EMBED', 'HR', 'IMG', 'INPUT', 'LINK', 'META', 'SOURCE', 'TRACK', 'WBR' );
/**
* Map of HTML tag names to WordPress block types.
*
* @var array
*/
const BLOCK_MAP = array(
'UL' => 'list',
'OL' => 'list',
'IMG' => 'image',
'BLOCKQUOTE' => 'quote',
'H1' => 'heading',
'H2' => 'heading',
'H3' => 'heading',
'H4' => 'heading',
'H5' => 'heading',
'H6' => 'heading',
'P' => 'paragraph',
'A' => 'paragraph',
'ABBR' => 'paragraph',
'B' => 'paragraph',
'CODE' => 'paragraph',
'EM' => 'paragraph',
'I' => 'paragraph',
'STRONG' => 'paragraph',
'SUB' => 'paragraph',
'SUP' => 'paragraph',
'SPAN' => 'paragraph',
'U' => 'paragraph',
'FIGURE' => 'image',
'HR' => 'separator',
);
/**
* Initialize the class, registering WordPress hooks.
*
* @return void
*/
public static function init() {
// This is already being called on the init hook, so just add it.
self::register_blocks();
self::register_patterns();
self::register_templates();
\add_action( 'pre_get_posts', array( self::class, 'filter_query_loop_vars' ) );
\add_action( 'load-post-new.php', array( self::class, 'handle_in_reply_to_get_param' ) );
\add_action( 'load-post-new.php', array( self::class, 'handle_quotation_of_get_param' ) );
// Add editor plugin.
\add_action( 'enqueue_block_editor_assets', array( self::class, 'enqueue_editor_assets' ) );
\add_action( 'rest_api_init', array( self::class, 'register_rest_fields' ) );
\add_filter( 'activitypub_import_mastodon_post_data', array( self::class, 'filter_import_mastodon_post_data' ), 10, 2 );
\add_filter( 'activitypub_attachments', array( self::class, 'add_stats_image_attachment' ), 10, 2 );
\add_action( 'activitypub_before_get_content', array( self::class, 'add_post_transformation_callbacks' ) );
\add_filter( 'activitypub_the_content', array( self::class, 'remove_post_transformation_callbacks' ) );
}
/**
* Enqueue the block editor assets.
*
* @return void
*/
public static function enqueue_editor_assets() {
$data = array(
'namespace' => ACTIVITYPUB_REST_NAMESPACE,
'defaultAvatarUrl' => ACTIVITYPUB_PLUGIN_URL . 'assets/img/mp.jpg',
'enabled' => array(
'blog' => ! is_user_type_disabled( 'blog' ),
'users' => ! is_user_type_disabled( 'user' ),
),
'profileUrls' => array(
'user' => \admin_url( 'profile.php#activitypub' ),
'blog' => \admin_url( 'options-general.php?page=activitypub&tab=blog-profile' ),
),
'showAvatars' => (bool) \get_option( 'show_avatars' ),
'defaultQuotePolicy' => \get_option( 'activitypub_default_quote_policy', ACTIVITYPUB_INTERACTION_POLICY_ANYONE ),
'objectType' => \get_option( 'activitypub_object_type', ACTIVITYPUB_DEFAULT_OBJECT_TYPE ),
'noteLength' => ACTIVITYPUB_NOTE_LENGTH,
'statsImageUrlEndpoint' => Stats_Image::is_available() ? \get_rest_url( null, ACTIVITYPUB_REST_NAMESPACE . '/stats/image-url/{user_id}/{year}' ) : '',
'reactionTypes' => self::get_reaction_types(),
);
\wp_localize_script( 'wp-editor', '_activityPubOptions', $data );
// Check for our supported post types.
$current_screen = \get_current_screen();
$ap_post_types = \get_post_types_by_support( 'activitypub' );
if ( ! $current_screen || ! \in_array( $current_screen->post_type, $ap_post_types, true ) ) {
return;
}
$asset_data = include ACTIVITYPUB_PLUGIN_DIR . 'build/editor-plugin/plugin.asset.php';
$plugin_url = \plugins_url( 'build/editor-plugin/plugin.js', ACTIVITYPUB_PLUGIN_FILE );
\wp_enqueue_script( 'activitypub-block-editor', $plugin_url, $asset_data['dependencies'], $asset_data['version'], true );
$asset_data = include ACTIVITYPUB_PLUGIN_DIR . 'build/pre-publish-panel/plugin.asset.php';
$plugin_url = \plugins_url( 'build/pre-publish-panel/plugin.js', ACTIVITYPUB_PLUGIN_FILE );
\wp_enqueue_script( 'activitypub-pre-publish-panel', $plugin_url, $asset_data['dependencies'], $asset_data['version'], true );
}
/**
* Enqueue the reply handle script if the in_reply_to GET param is set.
*
* @return void
*/
public static function handle_in_reply_to_get_param() {
self::enqueue_intent_script( 'in_reply_to', 'reply-intent' );
}
/**
* Enqueue an intent script when its URL parameter is present.
*
* The script reads the parameter itself and prefills the matching block, so nothing
* is read here beyond the presence of the parameter.
*
* @since 9.4.0
*
* @param string $param The URL parameter carrying the address.
* @param string $script The build folder and script handle suffix.
*
* @return void
*/
private static function enqueue_intent_script( $param, $script ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only, the script only prefills a block.
if ( ! isset( $_GET[ $param ] ) ) {
return;
}
$asset_data = include ACTIVITYPUB_PLUGIN_DIR . 'build/' . $script . '/plugin.asset.php';
$plugin_url = \plugins_url( 'build/' . $script . '/plugin.js', ACTIVITYPUB_PLUGIN_FILE );
\wp_enqueue_script( 'activitypub-' . $script, $plugin_url, $asset_data['dependencies'], $asset_data['version'], true );
}
/**
* Enqueue the quote intent script if the quotation_of GET param is set.
*
* @since 9.4.0
*
* @return void
*/
public static function handle_quotation_of_get_param() {
self::enqueue_intent_script( 'quotation_of', 'quote-intent' );
}
/**
* Register the blocks.
*
* @return void
*/
public static function register_blocks() {
\register_block_type_from_metadata( ACTIVITYPUB_PLUGIN_DIR . '/build/extra-fields' );
\register_block_type_from_metadata( ACTIVITYPUB_PLUGIN_DIR . '/build/follow-me' );
\register_block_type_from_metadata( ACTIVITYPUB_PLUGIN_DIR . '/build/followers' );
\register_block_type_from_metadata( ACTIVITYPUB_PLUGIN_DIR . '/build/posts-and-replies' );
\register_block_type_from_metadata( ACTIVITYPUB_PLUGIN_DIR . '/build/stats' );
// Only register the Following block if the Following feature is enabled.
if ( '1' === \get_option( 'activitypub_following_ui', '0' ) ) {
\register_block_type_from_metadata( ACTIVITYPUB_PLUGIN_DIR . '/build/following' );
}
// Register reactions block, conditionally removing facepile style if avatars are disabled.
$reactions_args = array();
if ( ! \get_option( 'show_avatars', true ) ) {
// Compact is the default then, so only Counts is left to pick.
$reactions_args['styles'] = array(
array(
'name' => 'counts',
'label' => \__( 'Counts', 'activitypub' ),
),
);
}
\register_block_type_from_metadata( ACTIVITYPUB_PLUGIN_DIR . '/build/reactions', $reactions_args );
\register_block_type_from_metadata(
ACTIVITYPUB_PLUGIN_DIR . '/build/reply',
array(
'render_callback' => array( self::class, 'render_reply_block' ),
)
);
\register_block_type_from_metadata(
ACTIVITYPUB_PLUGIN_DIR . '/build/quote',
array(
'render_callback' => array( self::class, 'render_quote_block' ),
)
);
// Register remote media blocks (server-side only, no editor UI).
\register_block_type(
'activitypub/emoji',
array(
'attributes' => array(
'url' => array( 'type' => 'string' ),
'updated' => array( 'type' => 'string' ),
),
'render_callback' => array( self::class, 'render_emoji_block' ),
)
);
\register_block_type(
'activitypub/image',
array(
'attributes' => array(
'url' => array( 'type' => 'string' ),
'urlEncoded' => array( 'type' => 'boolean' ),
'alt' => array( 'type' => 'string' ),
),
'uses_context' => array( 'postId', 'commentId' ),
'render_callback' => array( self::class, 'render_image_block' ),
)
);
\register_block_type(
'activitypub/audio',
array(
'attributes' => array(
'url' => array( 'type' => 'string' ),
),
'render_callback' => array( self::class, 'render_audio_block' ),
)
);
\register_block_type(
'activitypub/video',
array(
'attributes' => array(
'url' => array( 'type' => 'string' ),
),
'render_callback' => array( self::class, 'render_video_block' ),
)
);
}
/**
* Register block patterns for ActivityPub.
*
* @return void
*/
public static function register_patterns() {
// Register the ActivityPub pattern category.
\register_block_pattern_category(
'activitypub',
array(
'label' => \__( 'Fediverse', 'activitypub' ),
)
);
// Register each pattern.
require ACTIVITYPUB_PLUGIN_DIR . '/patterns/author-header.php';
require ACTIVITYPUB_PLUGIN_DIR . '/patterns/author-profile.php';
require ACTIVITYPUB_PLUGIN_DIR . '/patterns/follow-page.php';
require ACTIVITYPUB_PLUGIN_DIR . '/patterns/profile-page.php';
require ACTIVITYPUB_PLUGIN_DIR . '/patterns/social-sidebar.php';
// Only register the Following page pattern if the Following feature is enabled.
if ( '1' === \get_option( 'activitypub_following_ui', '0' ) ) {
require ACTIVITYPUB_PLUGIN_DIR . '/patterns/following-page.php';
}
// Only register the Stats post starter pattern in December and January.
$month = (int) \gmdate( 'n' );
if ( 12 === $month || 1 === $month ) {
require ACTIVITYPUB_PLUGIN_DIR . '/patterns/stats-post.php';
}
}
/**
* Register FSE templates for block themes.
*
* @return void
*/
public static function register_templates() {
// Only register templates for block themes on WP 6.7+.
if ( ! \function_exists( 'register_block_template' ) || ! \wp_is_block_theme() ) {
return;
}
// Use the core `author` hierarchy slug so WP can resolve this for author archives.
\register_block_template(
'activitypub//author',
array(
'title' => \__( 'Author Archive (Fediverse)', 'activitypub' ),
'description' => \__( 'Displays an author archive with Fediverse profile and follow options.', 'activitypub' ),
'content' => '
',
'post_types' => array(),
)
);
}
/**
* Register REST fields needed for blocks.
*
* @return void
*/
public static function register_rest_fields() {
// Register the post_count field for Follow Me block.
\register_rest_field(
'user',
'post_count',
array(
/**
* Get the number of published posts.
*
* @param array $response Prepared response array.
* @param string $field_name The field name.
* @param \WP_REST_Request $request The request object.
* @return int The number of published posts.
*/
'get_callback' => static function ( $response, $field_name, $request ) {
return (int) \count_user_posts( $request->get_param( 'id' ), 'post', true );
},
'schema' => array(
'description' => 'Number of published posts',
'type' => 'integer',
'context' => array( 'activitypub' ),
),
)
);
// Tells the editor whether the post endpoints will answer for this post, so the Reactions block only asks when they do.
\register_rest_field(
\get_post_types_by_support( 'activitypub' ),
'activitypub_publicly_queryable',
array(
/**
* Whether the post is publicly queryable via ActivityPub.
*
* @param array $response Prepared response array.
* @return bool True if the post is publicly queryable.
*/
'get_callback' => static function ( $response ) {
return is_post_publicly_queryable( $response['id'] );
},
'schema' => array(
'description' => 'Whether the post is publicly queryable via ActivityPub',
'type' => 'boolean',
'context' => array( 'edit' ),
),
)
);
// Lets the Quote block show whether the quoted author accepted or declined.
\register_rest_field(
\get_post_types_by_support( 'activitypub' ),
'activitypub_quote',
array(
/**
* Quote handshake state for the editor.
*
* @param array $response Prepared response array.
* @return array { request: string|null, authorization: string|null, rejected: bool }
*/
'get_callback' => static function ( $response ) {
return array(
// The URL the answer was for: a stamp or a rejection says nothing about a URL the author never saw.
'request' => \get_post_meta( $response['id'], '_activitypub_quote_request', true ) ?: null,
'authorization' => \get_post_meta( $response['id'], '_activitypub_quote_authorization', true ) ?: null,
'rejected' => (bool) \get_post_meta( $response['id'], '_activitypub_quote_rejected', true ),
);
},
'schema' => array(
'description' => 'FEP-044f quote handshake state of the post',
'type' => 'object',
'context' => array( 'edit' ),
),
)
);
}
/**
* Get the user ID from a user string.
*
* @param string $user_string The user string. Can be a user ID, 'blog', or 'inherit'.
* @return int|null The user ID, or null if the 'inherit' string is not supported in this context.
*/
public static function get_user_id( $user_string ) {
if ( \is_numeric( $user_string ) ) {
return \absint( $user_string );
}
// If the user string is 'blog', return the Blog User ID.
if ( 'blog' === $user_string ) {
return Actors::BLOG_USER_ID;
}
// The only other value should be 'inherit', which means to use the query context to determine the User.
if ( 'inherit' !== $user_string ) {
return null;
}
// For a homepage/front page, if the Blog User is active, use it.
if ( ( \is_front_page() || \is_home() ) && ! is_user_type_disabled( 'blog' ) ) {
return Actors::BLOG_USER_ID;
}
// If we're in a loop, use the post author.
$author_id = \get_the_author_meta( 'ID' );
if ( $author_id ) {
return $author_id;
}
// For other pages, the queried object will clue us in.
$queried_object = \get_queried_object();
if ( ! $queried_object ) {
return null;
}
// If we're on a user archive page, use that user's ID.
if ( \is_a( $queried_object, 'WP_User' ) ) {
return $queried_object->ID;
}
// For a single post, use the post author's ID.
if ( \is_a( $queried_object, 'WP_Post' ) ) {
return \get_the_author_meta( 'ID' );
}
// We won't properly account for some conditions, like tag archives.
return null;
}
/**
* Render an actor list block (followers or following).
*
* @param string $endpoint The endpoint type ('followers' or 'following').
* @param array $attributes Block attributes.
* @param \WP_Block $block Block instance.
* @param string $content Block content.
*
* @return string|void The HTML to render, or void to render nothing.
*/
public static function render_actor_list_block( $endpoint, $attributes, $block, $content ) {
if ( is_activitypub_request() || \is_feed() ) {
return '';
}
$attributes = \wp_parse_args( $attributes );
$block_name = 'followers' === $endpoint ? \__( 'Followers', 'activitypub' ) : \__( 'Following', 'activitypub' );
if ( empty( $content ) ) {
// Fallback for v1.0.0 blocks.
/* translators: %s: Block type (Followers or Following) */
$_title = $attributes['title'] ?? \sprintf( \__( 'Fediverse %s', 'activitypub' ), $block_name );
$content = '
',
\esc_url( $attrs['url'] ),
\esc_attr__( 'This post is a response to the referenced content.', 'activitypub' ),
// translators: %s is the URL of the post being replied to.
\sprintf( \__( '↬%s', 'activitypub' ), \str_replace( array( 'https://', 'http://' ), '', \esc_url( $attrs['url'] ) ) )
);
return \sprintf( '
%2$s
', $wrapper_attrs, $inner );
}
/**
* Render the Quote block.
*
* @since 9.4.0
*
* @see https://indieweb.org/quotation
*
* @param array $attrs The block attributes.
* @param string $content The block inner content (unused).
* @param \WP_Block|null $block The block instance, used to resolve the post outside the loop.
*
* @return string|null The block HTML.
*/
public static function render_quote_block( $attrs, $content = '', $block = null ) {
if ( empty( $attrs['url'] ) ) {
return null;
}
$url = $attrs['url'];
$post_id = $block instanceof \WP_Block && ! empty( $block->context['postId'] ) ? (int) $block->context['postId'] : \get_the_ID();
// A rejection only covers the URL it was answered for; a new URL starts a new handshake.
$rejected = $post_id
&& \get_post_meta( $post_id, '_activitypub_quote_rejected', true )
&& \get_post_meta( $post_id, '_activitypub_quote_request', true ) === $url;
// A declined quote, an invalid ActivityPub URL, or a post the block context couldn't resolve (the
// rejection meta is then unreadable) is shown as a plain link the site does not vouch for.
$is_quote = $post_id && ! $rejected && ( $attrs['isValidActivityPub'] ?? true );
$show_embed = $is_quote && ! empty( $attrs['embedPost'] ) && ! is_activitypub_request() && ! \is_feed();
$wrapper_attrs = \get_block_wrapper_attributes(
array(
'aria-label' => \__( 'Quote', 'activitypub' ),
'class' => 'activitypub-quote-block u-quotation-of h-cite',
'data-quotation-of' => $url,
)
);
$embed = null;
if ( $show_embed ) {
$embed_width = ! empty( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : 600;
$embed = \wp_oembed_get( $url, array( 'width' => $embed_width ) );
if ( $embed ) {
\wp_enqueue_script( 'wp-embed' );
}
}
// The citation needs a link to the source at a minimum, and the card carries one already.
$link = \sprintf(
'
',
\esc_url( $url ),
\esc_html( \str_replace( array( 'https://', 'http://' ), '', $url ) )
);
// The embed carries the link, so it replaces it, the way the Reply block does it.
$inner = $embed ? $embed : $link;
return \sprintf( '
%2$s
', $wrapper_attrs, $inner );
}
/**
* Get the comment and reaction types the reactions block counts.
*
* Comments come first, with the labels core uses. The reaction types bring their icons and
* labels from the comment type registry.
*
* @since 9.4.0
*
* @return array[] Types keyed by comment type, each with `icon`, `count_single` and `count_plural`.
*/
public static function get_reaction_types() {
// Core's comment icon when it has one (WordPress 7.1+), else the bundled SVG.
$icon = \function_exists( 'wp_get_icon' ) ? \wp_get_icon( 'core/comment' ) : '';
$types = array(
'comment' => array(
'icon' => $icon ? $icon : '',
/* translators: %s: Number of comments. */
'count_single' => \_n( '%s Comment', '%s Comments', 1, 'default' ),
/* translators: %s: Number of comments. */
'count_plural' => \_n( '%s Comment', '%s Comments', 2, 'default' ),
),
);
foreach ( Comment::get_comment_types() as $slug => $type ) {
$types[ $slug ] = array(
'icon' => $type['icon'] ?? '',
'count_single' => $type['count_single'] ?? '',
'count_plural' => $type['count_plural'] ?? '',
);
}
return $types;
}
/**
* Renders a modal component that can be used by different blocks.
*
* @param array $args {
* Arguments for the modal.
*
* @type string $content The modal content HTML.
* @type string $id Optional ID prefix for the modal elements.
* @type bool $is_compact Whether the modal is compact (popover-style). Default false.
* @type string $title Static title text for the modal header.
* @type string $title_binding Optional Interactivity API binding for a dynamic title
* (e.g. 'context.modal.title'). When set, uses data-wp-text
* on the title element and enables dynamic compact toggling.
* }
*
* @return void
*/
public static function render_modal( $args = array() ) {
$defaults = array(
'content' => '',
'id' => '',
'is_compact' => false,
'title' => '',
'title_binding' => '',
);
$args = \wp_parse_args( $args, $defaults );
?>
` element that explains decentralized
* interactions to users unfamiliar with the Fediverse.
*
* @since 8.0.0
*
* @return void
*/
public static function render_modal_help() {
?>
',
\esc_url( $url ),
\esc_attr( $webfinger ),
\esc_html( '@' . \strtok( $webfinger, '@' ) )
);
}
/**
* Replace the Quote block with a plain link in the ActivityPub content.
*
* Receivers render the quoted post from the `quote` property; inlining the embed would duplicate it.
*
* @since 9.4.0
*
* @param string $block_content The block content.
* @param array $block The block data.
*
* @return string The link markup.
*/
public static function generate_quote_link( $block_content, $block ) {
if ( empty( $block['attrs']['url'] ) ) {
return '';
}
return \sprintf( '
', \esc_url( $block['attrs']['url'] ), \esc_html( $block['attrs']['url'] ) );
}
/**
* Add the stats image as an attachment when a post contains the stats block.
*
* Parses the post content for activitypub/stats blocks and appends each
* as an Image attachment to the ActivityPub object.
*
* @since 8.1.0
*
* @param array $attachments The existing attachments.
* @param \WP_Post $post The post object.
*
* @return array The attachments with stats images appended.
*/
public static function add_stats_image_attachment( $attachments, $post ) {
if ( ! Stats_Image::is_available() ) {
return $attachments;
}
/*
* The stats image intentionally bypasses the `activitypub_max_image_attachments`
* limit because it replaces the block content rather than being an inline image
* extracted from the post. It is always appended so that the share-pic is
* included in the federated activity regardless of the attachment cap.
*/
$blocks = \parse_blocks( $post->post_content );
$stats_blocks = self::find_blocks_recursive( $blocks, 'activitypub/stats' );
foreach ( $stats_blocks as $block ) {
$user_id = self::get_user_id( $block['attrs']['selectedUser'] ?? 'blog' );
if ( null === $user_id ) {
continue;
}
$year = (int) ( $block['attrs']['year'] ?? (int) \gmdate( 'Y' ) - 1 );
$url = Stats_Image::get_url( $user_id, $year );
if ( \is_wp_error( $url ) ) {
continue;
}
// Determine mime type from URL extension.
$mime_type = \str_ends_with( $url, '.webp' ) ? 'image/webp' : 'image/png';
$attachments[] = array(
'type' => 'Image',
'mediaType' => $mime_type,
'url' => $url,
'name' => \sprintf(
/* translators: %d: The year */
\__( 'Fediverse Stats %d', 'activitypub' ),
$year
),
);
}
return $attachments;
}
/**
* Recursively find blocks of a given type in a block tree.
*
* @since 8.1.0
*
* @param array $blocks The parsed blocks.
* @param string $block_name The block name to search for.
*
* @return array The matching blocks.
*/
private static function find_blocks_recursive( $blocks, $block_name ) {
$found = array();
foreach ( $blocks as $block ) {
if ( $block_name === $block['blockName'] ) {
$found[] = $block;
}
if ( ! empty( $block['innerBlocks'] ) ) {
$found = \array_merge( $found, self::find_blocks_recursive( $block['innerBlocks'], $block_name ) );
}
}
return $found;
}
/**
* Transform Embed blocks to block level link.
*
* Remote servers will simply drop iframe elements, rendering incomplete content.
*
* @see https://www.w3.org/TR/activitypub/#security-sanitizing-content
* @see https://www.w3.org/wiki/ActivityPub/Primer/HTML
*
* @param string $block_content The block content (html).
* @param object $block The block object.
*
* @return string A block level link
*/
public static function revert_embed_links( $block_content, $block ) {
if ( ! isset( $block['attrs']['url'] ) ) {
return $block_content;
}
// Escape once and reuse: the URL is also the visible link text, so it must be safe there too.
$url = \esc_url( $block['attrs']['url'] );
return '