modified file wp-piwik

This commit is contained in:
2026-06-03 21:29:22 +00:00
committed by Gitium
parent 57bccfdbd1
commit 769efed689
2556 changed files with 368982 additions and 126264 deletions

View File

@ -0,0 +1,378 @@
<?php
/**
* Actors collection file.
*
* @package Activitypub
*/
namespace Activitypub\Collection;
use WP_Error;
use WP_User_Query;
use Activitypub\Model\User;
use Activitypub\Model\Blog;
use Activitypub\Model\Application;
use function Activitypub\object_to_uri;
use function Activitypub\normalize_url;
use function Activitypub\normalize_host;
use function Activitypub\url_to_authorid;
use function Activitypub\is_user_type_disabled;
use function Activitypub\user_can_activitypub;
/**
* Actors collection.
*/
class Actors {
/**
* The ID of the Blog User.
*
* @var int
*/
const BLOG_USER_ID = 0;
/**
* The ID of the Application User.
*
* @var int
*/
const APPLICATION_USER_ID = -1;
/**
* Get the Actor by ID.
*
* @param int $user_id The User-ID.
*
* @return User|Blog|Application|WP_Error The Actor or WP_Error if user not found.
*/
public static function get_by_id( $user_id ) {
if ( is_numeric( $user_id ) ) {
$user_id = (int) $user_id;
}
if ( ! user_can_activitypub( $user_id ) ) {
return new WP_Error(
'activitypub_user_not_found',
\__( 'Actor not found', 'activitypub' ),
array( 'status' => 404 )
);
}
switch ( $user_id ) {
case self::BLOG_USER_ID:
return new Blog();
case self::APPLICATION_USER_ID:
return new Application();
default:
return User::from_wp_user( $user_id );
}
}
/**
* Get the Actor by username.
*
* @param string $username Name of the Actor.
*
* @return User|Blog|Application|WP_Error The Actor or WP_Error if user not found.
*/
public static function get_by_username( $username ) {
/**
* Filter the username before we do anything else.
*
* @param null $pre The pre-existing value.
* @param string $username The username.
*/
$pre = apply_filters( 'activitypub_pre_get_by_username', null, $username );
if ( null !== $pre ) {
return $pre;
}
// Check for blog user.
if ( Blog::get_default_username() === $username ) {
return new Blog();
}
if ( get_option( 'activitypub_blog_identifier' ) === $username ) {
return new Blog();
}
// Check for application user.
if ( 'application' === $username ) {
return new Application();
}
// Check for 'activitypub_username' meta.
$user = new WP_User_Query(
array(
'count_total' => false,
'number' => 1,
'hide_empty' => true,
'fields' => 'ID',
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_activitypub_user_identifier',
'value' => $username,
'compare' => 'LIKE',
),
),
)
);
if ( $user->results ) {
$actor = self::get_by_id( $user->results[0] );
if ( ! \is_wp_error( $actor ) ) {
return $actor;
}
}
$username = str_replace( array( '*', '%' ), '', $username );
// Check for login or nicename.
$user = new WP_User_Query(
array(
'count_total' => false,
'search' => $username,
'search_columns' => array( 'user_login', 'user_nicename' ),
'number' => 1,
'hide_empty' => true,
'fields' => 'ID',
)
);
if ( $user->results ) {
$actor = self::get_by_id( $user->results[0] );
if ( ! \is_wp_error( $actor ) ) {
return $actor;
}
}
return new WP_Error(
'activitypub_user_not_found',
\__( 'Actor not found', 'activitypub' ),
array( 'status' => 404 )
);
}
/**
* Get the Actor by resource.
*
* @param string $uri The Actor resource.
*
* @return User|Blog|Application|WP_Error The Actor or WP_Error if user not found.
*/
public static function get_by_resource( $uri ) {
$uri = object_to_uri( $uri );
if ( ! $uri ) {
return new WP_Error(
'activitypub_no_uri',
\__( 'No URI provided', 'activitypub' ),
array( 'status' => 404 )
);
}
$scheme = 'acct';
$match = array();
// Try to extract the scheme and the host.
if ( preg_match( '/^([a-zA-Z^:]+):(.*)$/i', $uri, $match ) ) {
// Extract the scheme.
$scheme = \esc_attr( $match[1] );
}
// @todo: handle old domain URIs here before we serve a new domain below when we shouldn't.
// Although maybe passing through to ::get_by_username() is enough?
switch ( $scheme ) {
// Check for http(s) URIs.
case 'http':
case 'https':
$resource_path = \wp_parse_url( $uri, PHP_URL_PATH );
if ( $resource_path ) {
$blog_path = \wp_parse_url( \home_url(), PHP_URL_PATH );
if ( $blog_path ) {
$resource_path = \str_replace( $blog_path, '', $resource_path );
}
$resource_path = \trim( $resource_path, '/' );
// Check for http(s)://blog.example.com/@username.
if ( str_starts_with( $resource_path, '@' ) ) {
$identifier = \str_replace( '@', '', $resource_path );
$identifier = \trim( $identifier, '/' );
return self::get_by_username( $identifier );
}
}
// Check for http(s)://blog.example.com/author/username.
$user_id = url_to_authorid( $uri );
if ( \is_int( $user_id ) ) {
return self::get_by_id( $user_id );
}
// Check for http(s)://blog.example.com/.
$normalized_uri = normalize_url( $uri );
if (
normalize_url( site_url() ) === $normalized_uri ||
normalize_url( home_url() ) === $normalized_uri
) {
return self::get_by_id( self::BLOG_USER_ID );
}
return new WP_Error(
'activitypub_no_user_found',
\__( 'Actor not found', 'activitypub' ),
array( 'status' => 404 )
);
// Check for acct URIs.
case 'acct':
$uri = \str_replace( 'acct:', '', $uri );
$identifier = \substr( $uri, 0, \strrpos( $uri, '@' ) );
$host = normalize_host( \substr( \strrchr( $uri, '@' ), 1 ) );
$blog_host = normalize_host( \wp_parse_url( \home_url( '/' ), \PHP_URL_HOST ) );
if ( $blog_host !== $host && get_option( 'activitypub_old_host' ) !== $host ) {
return new WP_Error(
'activitypub_wrong_host',
\__( 'Resource host does not match blog host', 'activitypub' ),
array( 'status' => 404 )
);
}
// Prepare wildcards https://github.com/mastodon/mastodon/issues/22213.
if ( in_array( $identifier, array( '_', '*', '' ), true ) ) {
return self::get_by_id( self::BLOG_USER_ID );
}
return self::get_by_username( $identifier );
default:
return new WP_Error(
'activitypub_wrong_scheme',
\__( 'Wrong scheme', 'activitypub' ),
array( 'status' => 404 )
);
}
}
/**
* Get the Actor by resource.
*
* @param string $id The Actor resource.
*
* @return User|Blog|Application|WP_Error The Actor or WP_Error if user not found.
*/
public static function get_by_various( $id ) {
$user = null;
if ( is_numeric( $id ) ) {
$user = self::get_by_id( $id );
} elseif (
// Is URL.
filter_var( $id, FILTER_VALIDATE_URL ) ||
// Is acct.
str_starts_with( $id, 'acct:' ) ||
// Is email.
filter_var( $id, FILTER_VALIDATE_EMAIL )
) {
$user = self::get_by_resource( $id );
} else {
$user = self::get_by_username( $id );
}
return $user;
}
/**
* Get the Actor collection.
*
* @return array The Actor collection.
*/
public static function get_collection() {
if ( is_user_type_disabled( 'user' ) ) {
return array();
}
$users = \get_users(
array(
'capability__in' => array( 'activitypub' ),
)
);
$return = array();
foreach ( $users as $user ) {
$actor = User::from_wp_user( $user->ID );
if ( \is_wp_error( $actor ) ) {
continue;
}
$return[] = $actor;
}
return $return;
}
/**
* Get all active Actors including the Blog Actor.
*
* @return array The actor collection.
*/
public static function get_all() {
$return = array();
if ( ! is_user_type_disabled( 'user' ) ) {
$users = \get_users(
array(
'capability__in' => array( 'activitypub' ),
)
);
foreach ( $users as $user ) {
$actor = User::from_wp_user( $user->ID );
if ( \is_wp_error( $actor ) ) {
continue;
}
$return[] = $actor;
}
}
// Also include the blog actor if active.
if ( ! is_user_type_disabled( 'blog' ) ) {
$blog_actor = self::get_by_id( self::BLOG_USER_ID );
if ( ! \is_wp_error( $blog_actor ) ) {
$return[] = $blog_actor;
}
}
return $return;
}
/**
* Returns the actor type based on the user ID.
*
* @param int $user_id The user ID to check.
* @return string The user type.
*/
public static function get_type_by_id( $user_id ) {
$user_id = (int) $user_id;
if ( self::APPLICATION_USER_ID === $user_id ) {
return 'application';
}
if ( self::BLOG_USER_ID === $user_id ) {
return 'blog';
}
return 'user';
}
}

View File

@ -0,0 +1,300 @@
<?php
/**
* Extra Fields collection file.
*
* @package Activitypub
*/
namespace Activitypub\Collection;
use Activitypub\Link;
use function Activitypub\site_supports_blocks;
/**
* Extra Fields collection.
*/
class Extra_Fields {
const USER_POST_TYPE = 'ap_extrafield';
const BLOG_POST_TYPE = 'ap_extrafield_blog';
/**
* Get the extra fields for a user.
*
* @param int $user_id The user ID.
*
* @return \WP_Post[] The extra fields.
*/
public static function get_actor_fields( $user_id ) {
$is_blog = self::is_blog( $user_id );
$post_type = $is_blog ? self::BLOG_POST_TYPE : self::USER_POST_TYPE;
$args = array(
'post_type' => $post_type,
'nopaging' => true,
'orderby' => 'menu_order',
'order' => 'ASC',
);
if ( ! $is_blog ) {
$args['author'] = $user_id;
}
$query = new \WP_Query( $args );
$fields = $query->posts ?? array();
/**
* Filters the extra fields for an ActivityPub actor.
*
* This filter allows developers to modify or add custom fields to an actor's
* profile.
*
* @param \WP_Post[] $fields Array of WP_Post objects representing the extra fields.
* @param int $user_id The ID of the user whose fields are being retrieved.
*/
return apply_filters( 'activitypub_get_actor_extra_fields', $fields, $user_id );
}
/**
* Get formatted content for an extra field.
*
* @param \WP_Post $post The post.
*
* @return string The formatted content.
*/
public static function get_formatted_content( $post ) {
$content = \get_the_content( null, false, $post );
$content = Link::the_content( $content );
if ( site_supports_blocks() ) {
$content = \do_blocks( $content );
}
$content = \wptexturize( $content );
$content = \wp_filter_content_tags( $content );
// Replace script and style elements.
$content = \preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $content );
$content = \strip_shortcodes( $content );
$content = \trim( \preg_replace( '/[\n\r\t]/', '', $content ) );
/**
* Filters the content of an extra field.
*
* @param string $content The content.
* @param \WP_Post $post The post.
*/
return \apply_filters( 'activitypub_extra_field_content', $content, $post );
}
/**
* Transforms the Extra Fields (Custom Post Types) to ActivityPub Actor-Attachments.
*
* @param \WP_Post[] $fields The extra fields.
*
* @return array ActivityPub attachments.
*/
public static function fields_to_attachments( $fields ) {
$attachments = array();
\add_filter( 'activitypub_link_rel', array( self::class, 'add_rel_me' ) );
foreach ( $fields as $post ) {
$content = self::get_formatted_content( $post );
$attachments[] = array(
'type' => 'PropertyValue',
'name' => \get_the_title( $post ),
'value' => \html_entity_decode(
$content,
\ENT_QUOTES,
'UTF-8'
),
);
$attachment = false;
// Add support for FEP-fb2a, for more information see FEDERATION.md.
$link_content = \trim( \strip_tags( $content, '<a>' ) );
if (
\stripos( $link_content, '<a' ) === 0 &&
\stripos( $link_content, '<a', 3 ) === false &&
\stripos( $link_content, '</a>', \strlen( $link_content ) - 4 ) !== false &&
\class_exists( '\WP_HTML_Tag_Processor' )
) {
$tags = new \WP_HTML_Tag_Processor( $link_content );
$tags->next_tag( 'A' );
if ( 'A' === $tags->get_tag() ) {
$attachment = array(
'type' => 'Link',
'name' => \get_the_title( $post ),
'href' => \esc_url( $tags->get_attribute( 'href' ) ),
);
$rel = $tags->get_attribute( 'rel' );
if ( $rel && \is_string( $rel ) ) {
$attachment['rel'] = \explode( ' ', $rel );
}
}
}
if ( ! $attachment ) {
$attachment = array(
'type' => 'Note',
'name' => \get_the_title( $post ),
'content' => \html_entity_decode(
$content,
\ENT_QUOTES,
'UTF-8'
),
);
}
$attachments[] = $attachment;
}
\remove_filter( 'activitypub_link_rel', array( self::class, 'add_rel_me' ) );
return $attachments;
}
/**
* Check if a post type is an extra fields post type.
*
* @param string $post_type The post type.
*
* @return bool True if the post type is an extra fields post type, otherwise false.
*/
public static function is_extra_fields_post_type( $post_type ) {
return \in_array( $post_type, array( self::USER_POST_TYPE, self::BLOG_POST_TYPE ), true );
}
/**
* Check if a post type is the `ap_extrafield` post type.
*
* @param string $post_type The post type.
*
* @return bool True if the post type is `ap_extrafield`, otherwise false.
*/
public static function is_extra_field_post_type( $post_type ) {
return self::USER_POST_TYPE === $post_type;
}
/**
* Check if a post type is the `ap_extrafield_blog` post type.
*
* @param string $post_type The post type.
*
* @return bool True if the post type is `ap_extrafield_blog`, otherwise false.
*/
public static function is_extra_field_blog_post_type( $post_type ) {
return self::BLOG_POST_TYPE === $post_type;
}
/**
* Add default extra fields to an actor.
*
* @param array $extra_fields The extra fields.
* @param int $user_id The User-ID.
*
* @return array The extra fields.
*/
public static function default_actor_extra_fields( $extra_fields, $user_id ) {
// We'll only take action when there are none yet.
if ( ! empty( $extra_fields ) ) {
return $extra_fields;
}
$is_blog = self::is_blog( $user_id );
$already_migrated = $is_blog
? \get_option( 'activitypub_default_extra_fields' )
: \get_user_meta( $user_id, 'activitypub_default_extra_fields', true );
if ( $already_migrated ) {
return $extra_fields;
}
\add_filter(
'activitypub_link_rel',
function ( $rel ) {
$rel .= ' me';
return $rel;
}
);
$defaults = array(
\__( 'Blog', 'activitypub' ) => \home_url( '/' ),
);
if ( ! $is_blog ) {
$author_url = \get_the_author_meta( 'user_url', $user_id );
$author_posts_url = \get_author_posts_url( $user_id );
$defaults[ \__( 'Profile', 'activitypub' ) ] = $author_posts_url;
if ( $author_url !== $author_posts_url ) {
$defaults[ \__( 'Homepage', 'activitypub' ) ] = $author_url;
}
}
$post_type = $is_blog ? self::BLOG_POST_TYPE : self::USER_POST_TYPE;
$menu_order = 10;
foreach ( $defaults as $title => $url ) {
if ( ! $url ) {
continue;
}
$extra_field = array(
'post_type' => $post_type,
'post_title' => $title,
'post_status' => 'publish',
'post_author' => $user_id,
'post_content' => self::make_paragraph_block( Link::the_content( $url ) ),
'comment_status' => 'closed',
'menu_order' => $menu_order,
);
$menu_order += 10;
$extra_field_id = wp_insert_post( $extra_field );
$extra_fields[] = get_post( $extra_field_id );
}
$is_blog
? \update_option( 'activitypub_default_extra_fields', true )
: \update_user_meta( $user_id, 'activitypub_default_extra_fields', true );
return $extra_fields;
}
/**
* Create a paragraph block.
*
* @param string $content The content.
*
* @return string The paragraph block.
*/
public static function make_paragraph_block( $content ) {
if ( ! site_supports_blocks() ) {
return $content;
}
return '<!-- wp:paragraph --><p>' . $content . '</p><!-- /wp:paragraph -->';
}
/**
* Add the 'me' rel to the link.
*
* @param string $rel The rel attribute.
* @return string The modified rel attribute.
*/
public static function add_rel_me( $rel ) {
return $rel . ' me';
}
/**
* Checks if the user is the blog user.
*
* @param int $user_id The user ID.
* @return bool True if the user is the blog user, otherwise false.
*/
private static function is_blog( $user_id ) {
return Actors::BLOG_USER_ID === $user_id;
}
}

View File

@ -0,0 +1,482 @@
<?php
/**
* Followers collection file.
*
* @package Activitypub
*/
namespace Activitypub\Collection;
use Activitypub\Model\Follower;
use WP_Error;
use WP_Query;
use function Activitypub\is_tombstone;
use function Activitypub\get_remote_metadata_by_actor;
/**
* ActivityPub Followers Collection.
*
* @author Matt Wiebe
* @author Matthias Pfefferle
*/
class Followers {
const POST_TYPE = 'ap_follower';
const CACHE_KEY_INBOXES = 'follower_inboxes_%s';
/**
* Add new Follower.
*
* @param int $user_id The ID of the WordPress User.
* @param string $actor The Actor URL.
*
* @return Follower|WP_Error The Follower (WP_Post array) or an WP_Error.
*/
public static function add_follower( $user_id, $actor ) {
$meta = get_remote_metadata_by_actor( $actor );
if ( is_tombstone( $meta ) ) {
return $meta;
}
if ( empty( $meta ) || ! is_array( $meta ) || is_wp_error( $meta ) ) {
return new WP_Error( 'activitypub_invalid_follower', __( 'Invalid Follower', 'activitypub' ), array( 'status' => 400 ) );
}
$follower = new Follower();
$follower->from_array( $meta );
$id = $follower->upsert();
if ( is_wp_error( $id ) ) {
return $id;
}
$post_meta = get_post_meta( $id, '_activitypub_user_id', false );
// phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
if ( is_array( $post_meta ) && ! in_array( $user_id, $post_meta ) ) {
add_post_meta( $id, '_activitypub_user_id', $user_id );
wp_cache_delete( sprintf( self::CACHE_KEY_INBOXES, $user_id ), 'activitypub' );
}
return $follower;
}
/**
* Remove a Follower.
*
* @param int $user_id The ID of the WordPress User.
* @param string $actor The Actor URL.
*
* @return bool True on success, false on failure.
*/
public static function remove_follower( $user_id, $actor ) {
wp_cache_delete( sprintf( self::CACHE_KEY_INBOXES, $user_id ), 'activitypub' );
$follower = self::get_follower( $user_id, $actor );
if ( ! $follower ) {
return false;
}
/**
* Fires before a Follower is removed.
*
* @param Follower $follower The Follower object.
* @param int $user_id The ID of the WordPress User.
* @param string $actor The Actor URL.
*/
do_action( 'activitypub_followers_pre_remove_follower', $follower, $user_id, $actor );
return delete_post_meta( $follower->get__id(), '_activitypub_user_id', $user_id );
}
/**
* Get a Follower.
*
* @param int $user_id The ID of the WordPress User.
* @param string $actor The Actor URL.
*
* @return Follower|false|null The Follower object or null
*/
public static function get_follower( $user_id, $actor ) {
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$post_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT DISTINCT p.ID FROM $wpdb->posts p INNER JOIN $wpdb->postmeta pm ON p.ID = pm.post_id WHERE p.post_type = %s AND pm.meta_key = '_activitypub_user_id' AND pm.meta_value = %d AND p.guid = %s",
array(
esc_sql( self::POST_TYPE ),
esc_sql( $user_id ),
esc_sql( $actor ),
)
)
);
if ( $post_id ) {
$post = get_post( $post_id );
return Follower::init_from_cpt( $post );
}
return null;
}
/**
* Get a Follower by Actor independent of the User.
*
* @param string $actor The Actor URL.
*
* @return Follower|false|null The Follower object or false on failure.
*/
public static function get_follower_by_actor( $actor ) {
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery
$post_id = $wpdb->get_var(
$wpdb->prepare(
"SELECT ID FROM $wpdb->posts WHERE guid=%s",
esc_sql( $actor )
)
);
if ( $post_id ) {
$post = get_post( $post_id );
return Follower::init_from_cpt( $post );
}
return null;
}
/**
* Get the Followers of a given user.
*
* @param int $user_id The ID of the WordPress User.
* @param int $number Maximum number of results to return.
* @param int $page Page number.
* @param array $args The WP_Query arguments.
* @return Follower[] List of `Follower` objects.
*/
public static function get_followers( $user_id, $number = -1, $page = null, $args = array() ) {
$data = self::get_followers_with_count( $user_id, $number, $page, $args );
return $data['followers'];
}
/**
* Get the Followers of a given user, along with a total count for pagination purposes.
*
* @param int $user_id The ID of the WordPress User.
* @param int $number Maximum number of results to return.
* @param int $page Page number.
* @param array $args The WP_Query arguments.
*
* @return array {
* Data about the followers.
*
* @type Follower[] $followers List of `Follower` objects.
* @type int $total Total number of followers.
* }
*/
public static function get_followers_with_count( $user_id, $number = -1, $page = null, $args = array() ) {
$defaults = array(
'post_type' => self::POST_TYPE,
'posts_per_page' => $number,
'paged' => $page,
'orderby' => 'ID',
'order' => 'DESC',
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
array(
'key' => '_activitypub_user_id',
'value' => $user_id,
),
),
);
$args = wp_parse_args( $args, $defaults );
$query = new WP_Query( $args );
$total = $query->found_posts;
$followers = array_map( array( Follower::class, 'init_from_cpt' ), $query->get_posts() );
$followers = array_filter( $followers );
return compact( 'followers', 'total' );
}
/**
* Get all Followers.
*
* @return Follower[] The Term list of Followers.
*/
public static function get_all_followers() {
$args = array(
'nopaging' => true,
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_activitypub_inbox',
'compare' => 'EXISTS',
),
array(
'key' => '_activitypub_actor_json',
'compare' => 'EXISTS',
),
),
);
return self::get_followers( null, null, null, $args );
}
/**
* Count the total number of followers
*
* @param int $user_id The ID of the WordPress User.
*
* @return int The number of Followers
*/
public static function count_followers( $user_id ) {
$query = new WP_Query(
array(
'post_type' => self::POST_TYPE,
'fields' => 'ids',
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_activitypub_user_id',
'value' => $user_id,
),
array(
'key' => '_activitypub_inbox',
'compare' => 'EXISTS',
),
array(
'key' => '_activitypub_actor_json',
'compare' => 'EXISTS',
),
),
)
);
return $query->found_posts;
}
/**
* Returns all Inboxes for an Actor's Followers.
*
* @param int $user_id The ID of the WordPress User.
*
* @return array The list of Inboxes.
*/
public static function get_inboxes( $user_id ) {
$cache_key = sprintf( self::CACHE_KEY_INBOXES, $user_id );
$inboxes = wp_cache_get( $cache_key, 'activitypub' );
if ( $inboxes ) {
return $inboxes;
}
// Get all Followers of an ID of the WordPress User.
$posts = new WP_Query(
array(
'nopaging' => true,
'post_type' => self::POST_TYPE,
'fields' => 'ids',
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
'relation' => 'AND',
array(
'key' => '_activitypub_inbox',
'compare' => 'EXISTS',
),
array(
'key' => '_activitypub_user_id',
'value' => $user_id,
),
array(
'key' => '_activitypub_inbox',
'value' => '',
'compare' => '!=',
),
),
)
);
$posts = $posts->get_posts();
if ( ! $posts ) {
return array();
}
global $wpdb;
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$results = $wpdb->get_col(
$wpdb->prepare(
"SELECT DISTINCT meta_value FROM {$wpdb->postmeta}
WHERE post_id IN (" . implode( ', ', array_fill( 0, count( $posts ), '%d' ) ) . ")
AND meta_key = '_activitypub_inbox'
AND meta_value IS NOT NULL",
$posts
)
);
$inboxes = array_filter( $results );
wp_cache_set( $cache_key, $inboxes, 'activitypub' );
return $inboxes;
}
/**
* Get all Inboxes for a given Activity.
*
* @param string $json The ActivityPub Activity JSON.
* @param int $actor_id The WordPress Actor ID.
* @param int $batch_size Optional. The batch size. Default 50.
* @param int $offset Optional. The offset. Default 0.
*
* @return array The list of Inboxes.
*/
public static function get_inboxes_for_activity( $json, $actor_id, $batch_size = 50, $offset = 0 ) {
$inboxes = self::get_inboxes( $actor_id );
if ( self::maybe_add_inboxes_of_blog_user( $json, $actor_id ) ) {
$inboxes = array_fill_keys( $inboxes, 1 );
foreach ( self::get_inboxes( Actors::BLOG_USER_ID ) as $inbox ) {
$inboxes[ $inbox ] = 1;
}
$inboxes = array_keys( $inboxes );
}
return array_slice( $inboxes, $offset, $batch_size );
}
/**
* Maybe add Inboxes of the Blog User.
*
* @param string $json The ActivityPub Activity JSON.
* @param int $actor_id The WordPress Actor ID.
* @return bool True if the Inboxes of the Blog User should be added, false otherwise.
*/
public static function maybe_add_inboxes_of_blog_user( $json, $actor_id ) {
// Only if we're in both Blog and User modes.
if ( ACTIVITYPUB_ACTOR_AND_BLOG_MODE !== \get_option( 'activitypub_actor_mode', ACTIVITYPUB_ACTOR_MODE ) ) {
return false;
}
// Only if this isn't the Blog Actor.
if ( Actors::BLOG_USER_ID === $actor_id ) {
return false;
}
$activity = json_decode( $json, true );
// Only if this is an Update or Delete. Create handles its own "Announce" in dual user mode.
if ( ! in_array( $activity['type'] ?? null, array( 'Update', 'Delete' ), true ) ) {
return false;
}
return true;
}
/**
* Get all Followers that have not been updated for a given time.
*
* @param int $number Optional. Limits the result. Default 50.
* @param int $older_than Optional. The time in seconds. Default 86400 (1 day).
*
* @return Follower[] The Term list of Followers.
*/
public static function get_outdated_followers( $number = 50, $older_than = 86400 ) {
$args = array(
'post_type' => self::POST_TYPE,
'posts_per_page' => $number,
'orderby' => 'modified',
'order' => 'ASC',
'post_status' => 'any', // 'any' includes 'trash'.
'date_query' => array(
array(
'column' => 'post_modified_gmt',
'before' => gmdate( 'Y-m-d', \time() - $older_than ),
),
),
);
$posts = new WP_Query( $args );
$items = array_map( array( Follower::class, 'init_from_cpt' ), $posts->get_posts() );
return array_filter( $items );
}
/**
* Get all Followers that had errors.
*
* @param int $number Optional. The number of Followers to return. Default 20.
*
* @return Follower[] The Term list of Followers.
*/
public static function get_faulty_followers( $number = 20 ) {
$args = array(
'post_type' => self::POST_TYPE,
'posts_per_page' => $number,
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
'relation' => 'OR',
array(
'key' => '_activitypub_errors',
'compare' => 'EXISTS',
),
array(
'key' => '_activitypub_inbox',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_activitypub_actor_json',
'compare' => 'NOT EXISTS',
),
array(
'key' => '_activitypub_inbox',
'value' => '',
'compare' => '=',
),
array(
'key' => '_activitypub_actor_json',
'value' => '',
'compare' => '=',
),
),
);
$posts = new WP_Query( $args );
$items = array_map( array( Follower::class, 'init_from_cpt' ), $posts->get_posts() );
return array_filter( $items );
}
/**
* This function is used to store errors that occur when
* sending an ActivityPub message to a Follower.
*
* The error will be stored in post meta.
*
* @param int $post_id The ID of the WordPress Custom-Post-Type.
* @param mixed $error The error message. Can be a string or a WP_Error.
*
* @return int|false The meta ID on success, false on failure.
*/
public static function add_error( $post_id, $error ) {
if ( is_string( $error ) ) {
$error_message = $error;
} elseif ( is_wp_error( $error ) ) {
$error_message = $error->get_error_message();
} else {
$error_message = __(
'Unknown Error or misconfigured Error-Message',
'activitypub'
);
}
return add_post_meta(
$post_id,
'_activitypub_errors',
$error_message
);
}
}

View File

@ -0,0 +1,349 @@
<?php
/**
* Interactions collection file.
*
* @package Activitypub
*/
namespace Activitypub\Collection;
use Activitypub\Webfinger;
use WP_Comment_Query;
use Activitypub\Comment;
use function Activitypub\object_to_uri;
use function Activitypub\is_post_disabled;
use function Activitypub\url_to_commentid;
use function Activitypub\object_id_to_comment;
use function Activitypub\get_remote_metadata_by_actor;
/**
* ActivityPub Interactions Collection.
*/
class Interactions {
const INSERT = 'insert';
const UPDATE = 'update';
/**
* Add a comment to a post.
*
* @param array $activity The activity-object.
*
* @return int|false|\WP_Error The comment ID or false or WP_Error on failure.
*/
public static function add_comment( $activity ) {
$commentdata = self::activity_to_comment( $activity );
if ( ! $commentdata || ! isset( $activity['object']['inReplyTo'] ) ) {
return false;
}
$in_reply_to = object_to_uri( $activity['object']['inReplyTo'] );
$in_reply_to = \esc_url_raw( $in_reply_to );
$comment_post_id = \url_to_postid( $in_reply_to );
$parent_comment_id = url_to_commentid( $in_reply_to );
// Save only replies and reactions.
if ( ! $comment_post_id && $parent_comment_id ) {
$parent_comment = get_comment( $parent_comment_id );
$comment_post_id = $parent_comment->comment_post_ID;
}
if ( is_post_disabled( $comment_post_id ) ) {
return false;
}
$commentdata['comment_post_ID'] = $comment_post_id;
$commentdata['comment_parent'] = $parent_comment_id ? $parent_comment_id : 0;
return self::persist( $commentdata, self::INSERT );
}
/**
* Update a comment.
*
* @param array $activity The activity object.
*
* @return array|string|int|\WP_Error|false The comment data or false on failure.
*/
public static function update_comment( $activity ) {
$meta = get_remote_metadata_by_actor( $activity['actor'] );
// Determine comment_ID.
$comment = object_id_to_comment( \esc_url_raw( $activity['object']['id'] ) );
$commentdata = \get_comment( $comment, ARRAY_A );
if ( ! $commentdata ) {
return false;
}
// Found a local comment id.
$commentdata['comment_author'] = \esc_attr( $meta['name'] ? $meta['name'] : $meta['preferredUsername'] );
$commentdata['comment_content'] = \addslashes( $activity['object']['content'] );
return self::persist( $commentdata, self::UPDATE );
}
/**
* Adds an incoming Like, Announce, ... as a comment to a post.
*
* @param array $activity Activity array.
*
* @return array|false Comment data or `false` on failure.
*/
public static function add_reaction( $activity ) {
$commentdata = self::activity_to_comment( $activity );
if ( ! $commentdata ) {
return false;
}
$url = object_to_uri( $activity['object'] );
$comment_post_id = \url_to_postid( $url );
$parent_comment_id = url_to_commentid( $url );
if ( ! $comment_post_id && $parent_comment_id ) {
$parent_comment = \get_comment( $parent_comment_id );
$comment_post_id = $parent_comment->comment_post_ID;
}
if ( ! $comment_post_id || is_post_disabled( $comment_post_id ) ) {
// Not a reply to a post or comment.
return false;
}
$comment_type = Comment::get_comment_type_by_activity_type( $activity['type'] );
if ( ! $comment_type ) {
// Not a valid comment type.
return false;
}
$comment_content = $comment_type['excerpt'];
$commentdata['comment_post_ID'] = $comment_post_id;
$commentdata['comment_content'] = \esc_html( $comment_content );
$commentdata['comment_type'] = \esc_attr( $comment_type['type'] );
$commentdata['comment_meta']['source_id'] = \esc_url_raw( $activity['id'] );
return self::persist( $commentdata, self::INSERT );
}
/**
* Get interaction(s) for a given URL/ID.
*
* @param string $url The URL/ID to get interactions for.
*
* @return array The interactions as WP_Comment objects.
*/
public static function get_interaction_by_id( $url ) {
$args = array(
'nopaging' => true,
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'protocol',
'value' => 'activitypub',
),
array(
'relation' => 'OR',
array(
'key' => 'source_url',
'value' => $url,
),
array(
'key' => 'source_id',
'value' => $url,
),
),
),
);
$query = new WP_Comment_Query( $args );
return $query->comments;
}
/**
* Get interaction(s) for a given actor.
*
* @param string $actor The Actor-URL.
*
* @return array The interactions as WP_Comment objects.
*/
public static function get_interactions_by_actor( $actor ) {
$meta = get_remote_metadata_by_actor( $actor );
// Get URL, because $actor seems to be the ID.
if ( $meta && ! is_wp_error( $meta ) && isset( $meta['url'] ) ) {
$actor = object_to_uri( $meta['url'] );
}
$args = array(
'nopaging' => true,
'author_url' => $actor,
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => array(
array(
'key' => 'protocol',
'value' => 'activitypub',
),
),
);
return get_comments( $args );
}
/**
* Adds line breaks to the list of allowed comment tags.
*
* @param array $allowed_tags Allowed HTML tags.
* @param string $context Optional. Context. Default empty.
*
* @return array Filtered tag list.
*/
public static function allowed_comment_html( $allowed_tags, $context = '' ) {
if ( 'pre_comment_content' !== $context ) {
// Do nothing.
return $allowed_tags;
}
// Add `p` and `br` to the list of allowed tags.
if ( ! array_key_exists( 'br', $allowed_tags ) ) {
$allowed_tags['br'] = array();
}
if ( ! array_key_exists( 'p', $allowed_tags ) ) {
$allowed_tags['p'] = array();
}
return $allowed_tags;
}
/**
* Convert an Activity to a WP_Comment
*
* @param array $activity The Activity array.
*
* @return array|false The comment data or false on failure.
*/
public static function activity_to_comment( $activity ) {
$comment_content = null;
$actor = object_to_uri( $activity['actor'] ?? null );
$actor = get_remote_metadata_by_actor( $actor );
// Check Actor-Meta.
if ( ! $actor || is_wp_error( $actor ) ) {
return false;
}
// Check Actor-Name.
if ( isset( $actor['name'] ) ) {
$comment_author = $actor['name'];
} elseif ( isset( $actor['preferredUsername'] ) ) {
$comment_author = $actor['preferredUsername'];
} else {
return false;
}
$url = object_to_uri( $actor['url'] ?? $actor['id'] );
if ( ! $url ) {
$url = object_to_uri( $actor['id'] );
}
if ( isset( $activity['object']['content'] ) ) {
$comment_content = \addslashes( $activity['object']['content'] );
}
$webfinger = Webfinger::uri_to_acct( $url );
if ( is_wp_error( $webfinger ) ) {
$webfinger = '';
} else {
$webfinger = str_replace( 'acct:', '', $webfinger );
}
$commentdata = array(
'comment_author' => \esc_attr( $comment_author ),
'comment_author_url' => \esc_url_raw( $url ),
'comment_content' => $comment_content,
'comment_type' => 'comment',
'comment_author_email' => $webfinger,
'comment_meta' => array(
'source_id' => \esc_url_raw( object_to_uri( $activity['object'] ) ),
'protocol' => 'activitypub',
),
);
if ( isset( $actor['icon']['url'] ) ) {
$commentdata['comment_meta']['avatar_url'] = \esc_url_raw( $actor['icon']['url'] );
}
if ( isset( $activity['object']['url'] ) ) {
$commentdata['comment_meta']['source_url'] = \esc_url_raw( object_to_uri( $activity['object']['url'] ) );
}
return $commentdata;
}
/**
* Persist a comment.
*
* @param array $commentdata The commentdata array.
* @param string $action Optional. Either 'insert' or 'update'. Default 'insert'.
*
* @return array|string|int|\WP_Error|false The comment data or false on failure
*/
public static function persist( $commentdata, $action = self::INSERT ) {
// Disable flood control.
\remove_action( 'check_comment_flood', 'check_comment_flood_db' );
// Do not require email for AP entries.
\add_filter( 'pre_option_require_name_email', '__return_false' );
// No nonce possible for this submission route.
\add_filter(
'akismet_comment_nonce',
function () {
return 'inactive';
}
);
\add_filter( 'wp_kses_allowed_html', array( self::class, 'allowed_comment_html' ), 10, 2 );
if ( self::INSERT === $action ) {
$state = \wp_new_comment( $commentdata, true );
} else {
$state = \wp_update_comment( $commentdata, true );
}
\remove_filter( 'wp_kses_allowed_html', array( self::class, 'allowed_comment_html' ) );
\remove_filter( 'pre_option_require_name_email', '__return_false' );
// Restore flood control.
\add_action( 'check_comment_flood', 'check_comment_flood_db', 10, 4 );
if ( 1 === $state ) {
return $commentdata;
} else {
return $state; // Either WP_Comment, false, a WP_Error, 0, or 1!
}
}
/**
* Get the total number of interactions by type for a given ID.
*
* @param int $post_id The post ID.
* @param string $type The type of interaction to count.
*
* @return int The total number of interactions.
*/
public static function count_by_type( $post_id, $type ) {
return \get_comments(
array(
'post_id' => $post_id,
'status' => 'approve',
'type' => $type,
'count' => true,
'paging' => false,
'fields' => 'ids',
)
);
}
}

View File

@ -0,0 +1,351 @@
<?php
/**
* Outbox collection file.
*
* @package Activitypub
*/
namespace Activitypub\Collection;
use Activitypub\Dispatcher;
use Activitypub\Scheduler;
use Activitypub\Activity\Activity;
use Activitypub\Activity\Base_Object;
use function Activitypub\add_to_outbox;
/**
* ActivityPub Outbox Collection
*
* @link https://www.w3.org/TR/activitypub/#outbox
*/
class Outbox {
const POST_TYPE = 'ap_outbox';
/**
* Add an Item to the outbox.
*
* @param Activity $activity Full Activity object that will be added to the outbox.
* @param int $user_id The real or imaginary user ID of the actor that published the activity that will be added to the outbox.
* @param string $visibility Optional. The visibility of the content. Default: `ACTIVITYPUB_CONTENT_VISIBILITY_PUBLIC`. See `constants.php` for possible values: `ACTIVITYPUB_CONTENT_VISIBILITY_*`.
*
* @return false|int|\WP_Error The added item or an error.
*/
public static function add( Activity $activity, $user_id, $visibility = ACTIVITYPUB_CONTENT_VISIBILITY_PUBLIC ) {
$actor_type = Actors::get_type_by_id( $user_id );
$object_id = self::get_object_id( $activity );
$title = self::get_object_title( $activity->get_object() );
if ( ! $activity->get_actor() ) {
$activity->set_actor( Actors::get_by_id( $user_id )->get_id() );
}
$outbox_item = array(
'post_type' => self::POST_TYPE,
'post_title' => sprintf(
/* translators: 1. Activity type, 2. Object Title or Excerpt */
__( '[%1$s] %2$s', 'activitypub' ),
$activity->get_type(),
\wp_trim_words( $title, 5 )
),
'post_content' => wp_slash( $activity->to_json() ),
// ensure that user ID is not below 0.
'post_author' => \max( $user_id, 0 ),
'post_status' => 'pending',
'meta_input' => array(
'_activitypub_object_id' => $object_id,
'_activitypub_activity_type' => $activity->get_type(),
'_activitypub_activity_actor' => $actor_type,
'activitypub_content_visibility' => $visibility,
),
);
$has_kses = false !== \has_filter( 'content_save_pre', 'wp_filter_post_kses' );
if ( $has_kses ) {
// Prevent KSES from corrupting JSON in post_content.
\kses_remove_filters();
}
$id = \wp_insert_post( $outbox_item, true );
// Update the activity ID if the post was inserted successfully.
if ( $id && ! \is_wp_error( $id ) ) {
$activity->set_id( \get_the_guid( $id ) );
\wp_update_post(
array(
'ID' => $id,
'post_content' => \wp_slash( $activity->to_json() ),
)
);
}
if ( $has_kses ) {
\kses_init_filters();
}
if ( \is_wp_error( $id ) ) {
return $id;
}
if ( ! $id ) {
return false;
}
self::invalidate_existing_items( $object_id, $activity->get_type(), $id );
return $id;
}
/**
* Invalidate existing outbox items with the same activity type and object ID
* by setting their status to 'publish'.
*
* @param string $object_id The ID of the activity object.
* @param string $activity_type The type of the activity.
* @param int $current_id The ID of the current outbox item to exclude.
*
* @return void
*/
private static function invalidate_existing_items( $object_id, $activity_type, $current_id ) {
// Do not invalidate items for Announce activities.
if ( 'Announce' === $activity_type ) {
return;
}
$meta_query = array(
array(
'key' => '_activitypub_object_id',
'value' => $object_id,
),
);
// For non-Delete activities, only invalidate items of the same type.
if ( 'Delete' !== $activity_type ) {
$meta_query[] = array(
'key' => '_activitypub_activity_type',
'value' => $activity_type,
);
}
$existing_items = get_posts(
array(
'post_type' => self::POST_TYPE,
'post_status' => 'pending',
'exclude' => array( $current_id ),
// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'meta_query' => $meta_query,
'fields' => 'ids',
)
);
foreach ( $existing_items as $existing_item_id ) {
$event_args = array(
Dispatcher::$callback,
$existing_item_id,
Dispatcher::$batch_size,
\get_post_meta( $existing_item_id, '_activitypub_outbox_offset', true ) ?: 0, // phpcs:ignore
);
$timestamp = \wp_next_scheduled( 'activitypub_async_batch', $event_args );
\wp_unschedule_event( $timestamp, 'activitypub_async_batch', $event_args );
$timestamp = \wp_next_scheduled( 'activitypub_process_outbox', array( $existing_item_id ) );
\wp_unschedule_event( $timestamp, 'activitypub_process_outbox', array( $existing_item_id ) );
\wp_publish_post( $existing_item_id );
\delete_post_meta( $existing_item_id, '_activitypub_outbox_offset' );
}
}
/**
* Creates an Undo activity.
*
* @param int|\WP_Post $outbox_item The Outbox post or post ID.
*
* @return int|bool The ID of the outbox item or false on failure.
*/
public static function undo( $outbox_item ) {
$outbox_item = get_post( $outbox_item );
$activity = self::get_activity( $outbox_item );
$type = 'Undo';
if ( 'Create' === $activity->get_type() ) {
$type = 'Delete';
} elseif ( 'Add' === $activity->get_type() ) {
$type = 'Remove';
}
return add_to_outbox( $activity, $type, $outbox_item->post_author );
}
/**
* Reschedule an activity.
*
* @param int|\WP_Post $outbox_item The Outbox post or post ID.
*
* @return bool True if the activity was rescheduled, false otherwise.
*/
public static function reschedule( $outbox_item ) {
$outbox_item = get_post( $outbox_item );
$outbox_item->post_status = 'pending';
$outbox_item->post_date = current_time( 'mysql' );
wp_update_post( $outbox_item );
Scheduler::schedule_outbox_activity_for_federation( $outbox_item->ID );
return true;
}
/**
* Get the Activity object from the Outbox item.
*
* @param int|\WP_Post $outbox_item The Outbox post or post ID.
* @return Activity|\WP_Error The Activity object or WP_Error.
*/
public static function get_activity( $outbox_item ) {
$outbox_item = get_post( $outbox_item );
$actor = self::get_actor( $outbox_item );
if ( is_wp_error( $actor ) ) {
return $actor;
}
$activity_object = \json_decode( $outbox_item->post_content, true );
$type = \get_post_meta( $outbox_item->ID, '_activitypub_activity_type', true );
if ( $activity_object['type'] === $type ) {
$activity = Activity::init_from_array( $activity_object );
if ( ! $activity->get_actor() ) {
$activity->set_actor( $actor->get_id() );
}
} else {
$activity = new Activity();
$activity->set_type( $type );
$activity->set_id( $outbox_item->guid );
$activity->set_actor( $actor->get_id() );
// Pre-fill the Activity with data (for example cc and to).
$activity->set_object( $activity_object );
}
if ( 'Update' === $type ) {
$activity->set_updated( gmdate( ACTIVITYPUB_DATE_TIME_RFC3339, strtotime( $outbox_item->post_modified ) ) );
}
/**
* Filters the Activity object before it is returned.
*
* @param Activity $activity The Activity object.
* @param \WP_Post $outbox_item The outbox item post object.
*/
return apply_filters( 'activitypub_get_outbox_activity', $activity, $outbox_item );
}
/**
* Get the Actor object from the Outbox item.
*
* @param \WP_Post $outbox_item The Outbox post.
*
* @return \Activitypub\Model\User|\Activitypub\Model\Blog|\WP_Error The Actor object or WP_Error.
*/
public static function get_actor( $outbox_item ) {
$actor_type = \get_post_meta( $outbox_item->ID, '_activitypub_activity_actor', true );
switch ( $actor_type ) {
case 'blog':
$actor_id = Actors::BLOG_USER_ID;
break;
case 'application':
$actor_id = Actors::APPLICATION_USER_ID;
break;
case 'user':
default:
$actor_id = $outbox_item->post_author;
break;
}
return Actors::get_by_id( $actor_id );
}
/**
* Get the Activity object from the Outbox item.
*
* @param \WP_Post $outbox_item The Outbox post.
*
* @return Activity|\WP_Error The Activity object or WP_Error.
*/
public static function maybe_get_activity( $outbox_item ) {
if ( ! $outbox_item instanceof \WP_Post ) {
return new \WP_Error( 'invalid_outbox_item', 'Invalid Outbox item.' );
}
if ( 'ap_outbox' !== $outbox_item->post_type ) {
return new \WP_Error( 'invalid_outbox_item', 'Invalid Outbox item.' );
}
// Check if Outbox Activity is public.
$visibility = \get_post_meta( $outbox_item->ID, 'activitypub_content_visibility', true );
if ( ! in_array( $visibility, array( ACTIVITYPUB_CONTENT_VISIBILITY_PUBLIC, ACTIVITYPUB_CONTENT_VISIBILITY_QUIET_PUBLIC ), true ) ) {
return new \WP_Error( 'private_outbox_item', 'Not a public Outbox item.' );
}
$activity_types = \apply_filters( 'rest_activitypub_outbox_activity_types', array( 'Announce', 'Create', 'Like', 'Update' ) );
$activity_type = \get_post_meta( $outbox_item->ID, '_activitypub_activity_type', true );
if ( ! in_array( $activity_type, $activity_types, true ) ) {
return new \WP_Error( 'private_outbox_item', 'Not public Outbox item type.' );
}
return self::get_activity( $outbox_item );
}
/**
* Get the object ID of an activity.
*
* @param Activity|Base_Object|string $data The activity object.
*
* @return string The object ID.
*/
private static function get_object_id( $data ) {
$object = $data->get_object();
if ( is_object( $object ) ) {
return self::get_object_id( $object );
}
if ( is_string( $object ) ) {
return $object;
}
return $data->get_id() ?? $data->get_actor();
}
/**
* Get the title of an activity recursively.
*
* @param Base_Object $activity_object The activity object.
*
* @return string The title.
*/
private static function get_object_title( $activity_object ) {
if ( ! $activity_object ) {
return '';
}
if ( is_string( $activity_object ) ) {
$post_id = url_to_postid( $activity_object );
return $post_id ? get_the_title( $post_id ) : '';
}
$title = $activity_object->get_name() ?? $activity_object->get_content();
if ( ! $title && $activity_object->get_object() instanceof Base_Object ) {
$title = $activity_object->get_object()->get_name() ?? $activity_object->get_object()->get_content();
}
return $title;
}
}

View File

@ -0,0 +1,226 @@
<?php
/**
* Replies collection file.
*
* @package Activitypub
*/
namespace Activitypub\Collection;
use WP_Post;
use WP_Comment;
use WP_Error;
use Activitypub\Comment;
use Activitypub\Model\Blog;
use Activitypub\Transformer\Post as PostTransformer;
use Activitypub\Transformer\Comment as CommentTransformer;
use function Activitypub\is_post_disabled;
use function Activitypub\is_local_comment;
use function Activitypub\get_rest_url_by_path;
use function Activitypub\is_user_type_disabled;
/**
* Class containing code for getting replies Collections and CollectionPages of posts and comments.
*/
class Replies {
/**
* Build base arguments for fetching the comments of either a WordPress post or comment.
*
* @param WP_Post|WP_Comment|WP_Error $wp_object The post or comment to fetch replies for on success.
*/
private static function build_args( $wp_object ) {
$args = array(
'status' => 'approve',
'orderby' => 'comment_date_gmt',
'order' => 'ASC',
'type' => 'comment',
);
if ( $wp_object instanceof WP_Post ) {
$args['parent'] = 0; // TODO: maybe this is unnecessary.
$args['post_id'] = $wp_object->ID;
} elseif ( $wp_object instanceof WP_Comment ) {
$args['parent'] = $wp_object->comment_ID;
} else {
return new WP_Error();
}
return $args;
}
/**
* Get the replies collections ID.
*
* @param WP_Post|WP_Comment $wp_object The post or comment to fetch replies for.
*
* @return string|WP_Error The rest URL of the replies collection or WP_Error if the object is not a post or comment.
*/
private static function get_id( $wp_object ) {
if ( $wp_object instanceof WP_Post ) {
return get_rest_url_by_path( sprintf( 'posts/%d/replies', $wp_object->ID ) );
} elseif ( $wp_object instanceof WP_Comment ) {
return get_rest_url_by_path( sprintf( 'comments/%d/replies', $wp_object->comment_ID ) );
} else {
return new WP_Error( 'unsupported_object', 'The object is not a post or comment.' );
}
}
/**
* Get the Replies collection.
*
* @param WP_Post|WP_Comment $wp_object The post or comment to fetch replies for.
*
* @return array|\WP_Error|null An associative array containing the replies collection without JSON-LD context on success.
*/
public static function get_collection( $wp_object ) {
$id = self::get_id( $wp_object );
if ( is_wp_error( $id ) ) {
return \wp_is_serving_rest_request() ? $id : null;
}
$replies = array(
'id' => $id,
'type' => 'Collection',
);
$replies['first'] = self::get_collection_page( $wp_object, 1, $replies['id'] );
return $replies;
}
/**
* Returns a replies collection page as an associative array.
*
* @link https://www.w3.org/TR/activitystreams-vocabulary/#dfn-collectionpage
*
* @param WP_Post|WP_Comment $wp_object The post of comment the replies are for.
* @param int $page The current pagination page.
* @param string $part_of Optional. The collection id/url the returned CollectionPage belongs to. Default null.
*
* @return array|WP_Error|null A CollectionPage as an associative array on success, WP_Error or null on failure.
*/
public static function get_collection_page( $wp_object, $page, $part_of = null ) {
// Build initial arguments for fetching approved comments.
$args = self::build_args( $wp_object );
if ( is_wp_error( $args ) ) {
return \wp_is_serving_rest_request() ? $args : null;
}
// Retrieve the partOf if not already given.
$part_of = $part_of ?? self::get_id( $wp_object );
// If the collection page does not exist.
if ( is_wp_error( $part_of ) ) {
return \wp_is_serving_rest_request() ? $part_of : null;
}
// Get to total replies count.
$total_replies = \get_comments( array_merge( $args, array( 'count' => true ) ) );
// If set to zero, we get errors below. You need at least one comment per page, here.
$args['number'] = max( (int) \get_option( 'comments_per_page' ), 1 );
$args['offset'] = intval( $page - 1 ) * $args['number'];
// Get the ActivityPub ID's of the comments, without local-only comments.
$comment_ids = self::get_reply_ids( \get_comments( $args ) );
// Build the associative CollectionPage array.
$collection_page = array(
'id' => \add_query_arg( 'page', $page, $part_of ),
'type' => 'CollectionPage',
'partOf' => $part_of,
'items' => $comment_ids,
);
if ( ( $total_replies / $args['number'] ) > $page ) {
$collection_page['next'] = \add_query_arg( 'page', $page + 1, $part_of );
}
if ( $page > 1 ) {
$collection_page['prev'] = \add_query_arg( 'page', $page - 1, $part_of );
}
return $collection_page;
}
/**
* Get the context collection for a post.
*
* @param int $post_id The post ID.
*
* @return array|false The context for the post or false if the post is not found or disabled.
*/
public static function get_context_collection( $post_id ) {
$post = \get_post( $post_id );
if ( ! $post || is_post_disabled( $post_id ) ) {
return false;
}
$comments = \get_comments(
array(
'post_id' => $post_id,
'type' => 'comment',
'status' => 'approve',
'orderby' => 'comment_date_gmt',
'order' => 'ASC',
)
);
$ids = self::get_reply_ids( $comments, true );
$post_uri = ( new PostTransformer( $post ) )->to_id();
\array_unshift( $ids, $post_uri );
$author = Actors::get_by_id( $post->post_author );
if ( is_wp_error( $author ) ) {
if ( is_user_type_disabled( 'blog' ) ) {
return false;
}
$author = new Blog();
}
return array(
'type' => 'OrderedCollection',
'url' => \get_permalink( $post_id ),
'attributedTo' => $author->get_id(),
'totalItems' => count( $ids ),
'items' => $ids,
);
}
/**
* Get the ActivityPub ID's from a list of comments.
*
* It takes only federated/non-local comments into account, others also do not have an
* ActivityPub ID available.
*
* @param WP_Comment[] $comments The comments to retrieve the ActivityPub ids from.
* @param boolean $include_blog_comments Optional. Include blog comments in the returned array. Default false.
*
* @return string[] A list of the ActivityPub ID's.
*/
private static function get_reply_ids( $comments, $include_blog_comments = false ) {
$comment_ids = array();
foreach ( $comments as $comment ) {
if ( is_local_comment( $comment ) ) {
continue;
}
$public_comment_id = Comment::get_source_id( $comment->comment_ID );
if ( $public_comment_id ) {
$comment_ids[] = $public_comment_id;
continue;
}
if ( $include_blog_comments ) {
$comment_ids[] = ( new CommentTransformer( $comment ) )->to_id();
}
}
return \array_unique( $comment_ids );
}
}

View File

@ -0,0 +1,78 @@
<?php
/**
* Users collection file.
*
* @package Activitypub
*/
namespace Activitypub\Collection;
/**
* Users collection.
*
* @deprecated version 4.2.0
*/
class Users extends Actors {
/**
* Get the User by ID.
*
* @param int $user_id The User-ID.
*
* @return User|Blog|Application|WP_Error The User or WP_Error if user not found.
*/
public static function get_by_id( $user_id ) {
_deprecated_function( __METHOD__, '4.2.0', 'Activitypub\Collection\Actors::get_by_id' );
return parent::get_by_id( $user_id );
}
/**
* Get the User by username.
*
* @param string $username The User-Name.
*
* @return User|Blog|Application|WP_Error The User or WP_Error if user not found.
*/
public static function get_by_username( $username ) {
_deprecated_function( __METHOD__, '4.2.0', 'Activitypub\Collection\Actors::get_by_username' );
return parent::get_by_username( $username );
}
/**
* Get the User by resource.
*
* @param string $uri The User-Resource.
*
* @return User|WP_Error The User or WP_Error if user not found.
*/
public static function get_by_resource( $uri ) {
_deprecated_function( __METHOD__, '4.2.0', 'Activitypub\Collection\Actors::get_by_resource' );
return parent::get_by_resource( $uri );
}
/**
* Get the User by resource.
*
* @param string $id The User-Resource.
*
* @return User|Blog|Application|WP_Error The User or WP_Error if user not found.
*/
public static function get_by_various( $id ) {
_deprecated_function( __METHOD__, '4.2.0', 'Activitypub\Collection\Actors::get_by_various' );
return parent::get_by_various( $id );
}
/**
* Get the User collection.
*
* @return array The User collection.
*/
public static function get_collection() {
_deprecated_function( __METHOD__, '4.2.0', 'Activitypub\Collection\Actors::get_collection' );
return parent::get_collection();
}
}