Compare commits

..

7 commits

Author SHA1 Message Date
Matthias Pfefferle
bfbb6d515e add support for threaded comments 2023-11-13 16:58:04 +01:00
Matthias Pfefferle
15398e9ca1
Merge branch 'master' into add/activity-handler 2023-11-13 11:23:48 +01:00
Matthias Pfefferle
8a4cc72335 test new functions 2023-11-13 10:29:15 +01:00
Matthias Pfefferle
700cd59fb7 fix delete and add improve undo 2023-11-10 19:29:07 +01:00
Matthias Pfefferle
a29dc2ec1b save source id 2023-11-08 16:57:13 +01:00
Matthias Pfefferle
246c868b4b
Merge branch 'master' into add/activity-handler 2023-11-08 16:48:11 +01:00
Matthias Pfefferle
862bef1c16 init 2023-11-08 16:46:02 +01:00
45 changed files with 1530 additions and 1604 deletions

View file

@ -3,7 +3,7 @@
**Tags:** OStatus, fediverse, activitypub, activitystream
**Requires at least:** 4.7
**Tested up to:** 6.4
**Stable tag:** 1.2.0
**Stable tag:** 1.1.0
**Requires PHP:** 5.6
**License:** MIT
**License URI:** http://opensource.org/licenses/MIT
@ -105,15 +105,6 @@ Where 'blog' is the path to the subdirectory at which your blog resides.
Project maintained on GitHub at [automattic/wordpress-activitypub](https://github.com/automattic/wordpress-activitypub).
### 1.2.0 ###
* Add: Search and order followerer lists
* Add: Have a filter to defer signature verification
* Improved: "Follow Me" styles for dark themes
* Improved: Allow `p` and `br` tags only for AP comments
* Fixed: Deduplicate attachments earlier to prevent incorrect max_media
### 1.1.0 ###
* Improved: audio and video attachments are now supported!

View file

@ -3,7 +3,7 @@
* Plugin Name: ActivityPub
* Plugin URI: https://github.com/pfefferle/wordpress-activitypub/
* Description: The ActivityPub protocol is a decentralized social networking protocol based upon the ActivityStreams 2.0 data format.
* Version: 1.2.0
* Version: 1.1.0
* Author: Matthias Pfefferle & Automattic
* Author URI: https://automattic.com/
* License: MIT
@ -33,15 +33,12 @@ require_once __DIR__ . '/includes/functions.php';
\defined( 'ACTIVITYPUB_CUSTOM_POST_CONTENT' ) || \define( 'ACTIVITYPUB_CUSTOM_POST_CONTENT', "<strong>[ap_title]</strong>\n\n[ap_content]\n\n[ap_hashtags]\n\n[ap_shortlink]" );
\defined( 'ACTIVITYPUB_AUTHORIZED_FETCH' ) || \define( 'ACTIVITYPUB_AUTHORIZED_FETCH', false );
\defined( 'ACTIVITYPUB_DISABLE_REWRITES' ) || \define( 'ACTIVITYPUB_DISABLE_REWRITES', false );
\defined( 'ACTIVITYPUB_DEFAULT_TRANSFORMER' ) || \define( 'ACTIVITYPUB_DEFAULT_TRANSFORMER', 'activitypub/default' );
\define( 'ACTIVITYPUB_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
\define( 'ACTIVITYPUB_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
\define( 'ACTIVITYPUB_PLUGIN_FILE', plugin_dir_path( __FILE__ ) . '/' . basename( __FILE__ ) );
\define( 'ACTIVITYPUB_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
/**
* Initialize REST routes.
*/
@ -69,7 +66,7 @@ function plugin_init() {
\add_action( 'init', array( __NAMESPACE__ . '\Migration', 'init' ) );
\add_action( 'init', array( __NAMESPACE__ . '\Activitypub', 'init' ) );
\add_action( 'init', array( __NAMESPACE__ . '\Activity_Dispatcher', 'init' ) );
\add_action( 'init', array( __NAMESPACE__ . '\Collection\Followers', 'init' ) );
\add_action( 'init', array( __NAMESPACE__ . '\Handler', 'init' ) );
\add_action( 'init', array( __NAMESPACE__ . '\Admin', 'init' ) );
\add_action( 'init', array( __NAMESPACE__ . '\Hashtag', 'init' ) );
\add_action( 'init', array( __NAMESPACE__ . '\Mention', 'init' ) );

View file

@ -15,7 +15,8 @@
"yoast/phpunit-polyfills": "^2.0",
"dealerdirect/phpcodesniffer-composer-installer": "^1.0.0",
"sirbrillig/phpcs-variable-analysis": "^2.11",
"phpcsstandards/phpcsextra": "^1.1.0"
"phpcsstandards/phpcsextra": "^1.1.0",
"dms/phpunit-arraysubset-asserts": "^0.4.0"
},
"config": {
"allow-plugins": true

View file

@ -194,6 +194,12 @@ class Activity extends Base_Object {
* @return void
*/
public function set_object( $object ) {
// convert array to object
if ( is_array( $object ) ) {
$object = Base_Object::init_from_array( $object );
}
// set object
$this->set( 'object', $object );
if ( ! is_object( $object ) ) {

View file

@ -585,7 +585,7 @@ class Base_Object {
foreach ( $array as $key => $value ) {
$key = camel_to_snake_case( $key );
$object->set( $key, $value );
call_user_func( array( $object, 'set_' . $key ), $value );
}
return $object;
@ -611,7 +611,7 @@ class Base_Object {
foreach ( $array as $key => $value ) {
if ( $value ) {
$key = camel_to_snake_case( $key );
$this->set( $key, $value );
call_user_func( array( $this, 'set_' . $key ), $value );
}
}
}

View file

@ -1,23 +0,0 @@
<?php
/**
* Inspired by the PHP ActivityPub Library by @Landrok
*
* @link https://github.com/landrok/activitypub
*/
namespace Activitypub\Activity;
use Activitypub\Activity\Base_Object;
/**
* Event is an implementation of one of the
* Activity Streams Event object type
*
* The Object is the primary base type for the Activity Streams
* vocabulary.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-event
*/
class Note extends Base_Object {
protected $type = 'Event';
}

View file

@ -1,23 +0,0 @@
<?php
/**
* Inspired by the PHP ActivityPub Library by @Landrok
*
* @link https://github.com/landrok/activitypub
*/
namespace Activitypub\Activity;
use Activitypub\Activity\Base_Object;
/**
* Note is an implementation of one of the
* Activity Streams Note object type
*
* The Object is the primary base type for the Activity Streams
* vocabulary.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-note
*/
class Note extends Base_Object {
protected $type = 'Note';
}

View file

@ -5,7 +5,7 @@ use WP_Post;
use Activitypub\Activity\Activity;
use Activitypub\Collection\Users;
use Activitypub\Collection\Followers;
use Activitypub\Transformer\Transformers_Manager;
use Activitypub\Transformer\Post;
use function Activitypub\is_single_user;
use function Activitypub\is_user_disabled;
@ -65,8 +65,7 @@ class Activity_Dispatcher {
return;
}
$transformer = Transformers_Manager::instance()->get_transformer( $wp_post );
$object = $transformer->to_object();
$object = Post::transform( $wp_post )->to_object();
$activity = new Activity();
$activity->set_type( $type );
@ -102,8 +101,7 @@ class Activity_Dispatcher {
return;
}
$transformer = Transformers_Manager::instance()->get_transformer( $wp_post );
$object = $transformer->to_object();
$object = Post::transform( $wp_post )->to_object();
$activity = new Activity();
$activity->set_type( 'Announce' );

View file

@ -1,8 +1,12 @@
<?php
namespace Activitypub;
use Exception;
use Activitypub\Signature;
use Activitypub\Collection\Users;
use Activitypub\Collection\Followers;
use function Activitypub\sanitize_url;
/**
* ActivityPub Class
@ -20,9 +24,9 @@ class Activitypub {
\add_filter( 'get_comment_link', array( self::class, 'remote_comment_link' ), 11, 3 );
// Add support for ActivityPub to custom post types
$transformer_mapping = \get_option( 'activitypub_transformer_mapping', array( 'post' => 'activitypub/default', 'page' => 'activitypub/default' ) ) ? \get_option( 'activitypub_transformer_mapping', array( 'post' => 'activitypub/default', 'page' => 'activitypub/default' ) ) : array();
$post_types = \get_option( 'activitypub_support_post_types', array( 'post', 'page' ) ) ? \get_option( 'activitypub_support_post_types', array( 'post', 'page' ) ) : array();
foreach ( array_keys( $transformer_mapping ) as $post_type ) {
foreach ( $post_types as $post_type ) {
\add_post_type_support( $post_type, 'activitypub' );
}
@ -34,6 +38,9 @@ class Activitypub {
\add_action( 'after_setup_theme', array( self::class, 'theme_compat' ), 99 );
\add_action( 'in_plugin_update_message-' . ACTIVITYPUB_PLUGIN_BASENAME, array( self::class, 'plugin_update_message' ) );
// register several post_types
self::register_post_types();
}
/**
@ -54,7 +61,6 @@ class Activitypub {
*/
public static function deactivate() {
self::flush_rewrite_rules();
Scheduler::deregister_schedules();
}
@ -328,4 +334,80 @@ class Activitypub {
)
);
}
/**
* Register the "Followers" Taxonomy
*
* @return void
*/
private static function register_post_types() {
register_post_type(
Followers::POST_TYPE,
array(
'labels' => array(
'name' => _x( 'Followers', 'post_type plural name', 'activitypub' ),
'singular_name' => _x( 'Follower', 'post_type single name', 'activitypub' ),
),
'public' => false,
'hierarchical' => false,
'rewrite' => false,
'query_var' => false,
'delete_with_user' => false,
'can_export' => true,
'supports' => array(),
)
);
register_post_meta(
Followers::POST_TYPE,
'activitypub_inbox',
array(
'type' => 'string',
'single' => true,
'sanitize_callback' => 'sanitize_url',
)
);
register_post_meta(
Followers::POST_TYPE,
'activitypub_errors',
array(
'type' => 'string',
'single' => false,
'sanitize_callback' => function( $value ) {
if ( ! is_string( $value ) ) {
throw new Exception( 'Error message is no valid string' );
}
return esc_sql( $value );
},
)
);
register_post_meta(
Followers::POST_TYPE,
'activitypub_user_id',
array(
'type' => 'string',
'single' => false,
'sanitize_callback' => function( $value ) {
return esc_sql( $value );
},
)
);
register_post_meta(
Followers::POST_TYPE,
'activitypub_actor_json',
array(
'type' => 'string',
'single' => true,
'sanitize_callback' => function( $value ) {
return sanitize_text_field( $value );
},
)
);
do_action( 'activitypub_after_register_post_type' );
}
}

View file

@ -3,7 +3,6 @@ namespace Activitypub;
use WP_User_Query;
use Activitypub\Model\Blog_User;
use Activitypub\Base\Transformer\Base as Transformer_Base;
/**
* ActivityPub Admin Class
@ -23,15 +22,6 @@ class Admin {
if ( ! is_user_disabled( get_current_user_id() ) ) {
\add_action( 'show_user_profile', array( self::class, 'add_profile' ) );
}
add_filter(
'activitypub/transformers/is_transformer_enabled',
function( $should_register, Transformer_Base $transformer_instance ) {
return ! Options::is_transformer_disabled( $transformer_instance->get_name() );
},
10,
2
);
}
/**
@ -164,47 +154,14 @@ class Admin {
'default' => '0',
)
);
/**
* Flexible activation of post_types together with mapping ActivityPub transformers.
*
* If a post-type is not mapped to any ActivtiyPub transformer it means it is not activated
* for ActivityPub federation.
*
* @since version_number_transformer_management_placeholder
*/
register_setting(
\register_setting(
'activitypub',
'activitypub_transformer_mapping',
'activitypub_support_post_types',
array(
'type' => 'array',
'default' => array(
'post' => 'note',
),
'show_in_rest' => array(
'schema' => array(
'type' => 'array',
'items' => array(
'type' => 'string',
),
),
),
'sanitize_callback' => function ( $value ) {
// Check if $value is an array
if ( ! is_array( $value ) ) {
return array();
}
$value_keys = array_keys( $value );
$all_public_post_types = \get_post_types( array( 'public' => true ), 'names' );
// Unset the keys that are missing in $keysToCheck
foreach ( array_diff( $value_keys, $all_public_post_types ) as $missing_key ) {
unset( $value[ $missing_key ] );
}
// var_dump($value);
return $value;
},
'type' => 'string',
'description' => \esc_html__( 'Enable ActivityPub support for post types', 'activitypub' ),
'show_in_rest' => true,
'default' => array( 'post', 'pages' ),
)
);
\register_setting(

View file

@ -0,0 +1,33 @@
<?php
namespace Activitypub;
use Activitypub\Handler\Create;
use Activitypub\Handler\Delete;
use Activitypub\Handler\Follow;
use Activitypub\Handler\Undo;
use Activitypub\Handler\Update;
/**
* Handler class.
*/
class Handler {
/**
* Initialize the class, registering WordPress hooks
*/
public static function init() {
self::register_handlers();
}
/**
* Register handlers.
*/
public static function register_handlers() {
Create::init();
Delete::init();
Follow::init();
Undo::init();
Update::init();
do_action( 'activitypub_register_handlers' );
}
}

View file

@ -4,7 +4,6 @@ namespace Activitypub;
use Activitypub\Activitypub;
use Activitypub\Model\Blog_User;
use Activitypub\Collection\Followers;
use Activitypub\Admin;
/**
* ActivityPub Migration Class
@ -115,30 +114,12 @@ class Migration {
if ( version_compare( $version_from_db, '1.0.0', '<' ) ) {
self::migrate_from_0_17();
}
if ( version_compare( $version_from_db, 'version_number_transformer_management_placeholder', '<' ) ) {
self::migrate_from_version_number_transformer_management_placeholder();
}
update_option( 'activitypub_db_version', self::get_target_version() );
self::unlock();
}
/**
* Updates the supported post type settings to the mapped transformer setting.
* TODO: Test this
* @return void
*/
private static function migrate_from_version_number_transformer_management_placeholder() {
$supported_post_types = \get_option( 'activitypub_support_post_types', array( 'post', 'page' ) );
Admin::register_settings();
$transformer_mapping = array();
foreach ( $supported_post_types as $supported_post_type ) {
$transformer_mapping[ $supported_post_type ] = ACTIVITYPUB_DEFAULT_TRANSFORMER;
}
update_option( 'activitypub_transformer_mapping', $transformer_mapping );
}
/**
* Updates the DB-schema of the followers-list
*

View file

@ -4,6 +4,7 @@ namespace Activitypub;
use Activitypub\Collection\Users;
use Activitypub\Collection\Followers;
use Activitypub\Transformer\Post;
/**
* ActivityPub Scheduler Class

View file

@ -41,14 +41,9 @@ class Webfinger {
* @return string|WP_Error The URL or WP_Error
*/
public static function resolve( $resource ) {
if ( ! $resource ) {
return null;
}
if ( ! preg_match( '/^@?' . ACTIVITYPUB_USERNAME_REGEXP . '$/i', $resource, $m ) ) {
return null;
}
$transient_key = 'activitypub_resolve_' . ltrim( $resource, '@' );
$link = \get_transient( $transient_key );

View file

@ -2,14 +2,10 @@
namespace Activitypub\Collection;
use WP_Error;
use Exception;
use WP_Query;
use Activitypub\Http;
use Activitypub\Webfinger;
use Activitypub\Model\Follower;
use Activitypub\Collection\Users;
use Activitypub\Activity\Activity;
use Activitypub\Activity\Base_Object;
use function Activitypub\is_tombstone;
use function Activitypub\get_remote_metadata_by_actor;
@ -24,136 +20,6 @@ class Followers {
const POST_TYPE = 'ap_follower';
const CACHE_KEY_INBOXES = 'follower_inboxes_%s';
/**
* Register WordPress hooks/actions and register Taxonomy
*
* @return void
*/
public static function init() {
// register "followers" post_type
self::register_post_type();
\add_action( 'activitypub_inbox_follow', array( self::class, 'handle_follow_request' ), 10, 2 );
\add_action( 'activitypub_inbox_undo', array( self::class, 'handle_undo_request' ), 10, 2 );
\add_action( 'activitypub_followers_post_follow', array( self::class, 'send_follow_response' ), 10, 4 );
}
/**
* Register the "Followers" Taxonomy
*
* @return void
*/
private static function register_post_type() {
register_post_type(
self::POST_TYPE,
array(
'labels' => array(
'name' => _x( 'Followers', 'post_type plural name', 'activitypub' ),
'singular_name' => _x( 'Follower', 'post_type single name', 'activitypub' ),
),
'public' => false,
'hierarchical' => false,
'rewrite' => false,
'query_var' => false,
'delete_with_user' => false,
'can_export' => true,
'supports' => array(),
)
);
register_post_meta(
self::POST_TYPE,
'activitypub_inbox',
array(
'type' => 'string',
'single' => true,
'sanitize_callback' => array( self::class, 'sanitize_url' ),
)
);
register_post_meta(
self::POST_TYPE,
'activitypub_errors',
array(
'type' => 'string',
'single' => false,
'sanitize_callback' => function( $value ) {
if ( ! is_string( $value ) ) {
throw new Exception( 'Error message is no valid string' );
}
return esc_sql( $value );
},
)
);
register_post_meta(
self::POST_TYPE,
'activitypub_user_id',
array(
'type' => 'string',
'single' => false,
'sanitize_callback' => function( $value ) {
return esc_sql( $value );
},
)
);
register_post_meta(
self::POST_TYPE,
'activitypub_actor_json',
array(
'type' => 'string',
'single' => true,
'sanitize_callback' => function( $value ) {
return sanitize_text_field( $value );
},
)
);
do_action( 'activitypub_after_register_post_type' );
}
public static function sanitize_url( $value ) {
if ( filter_var( $value, FILTER_VALIDATE_URL ) === false ) {
return null;
}
return esc_url_raw( $value );
}
/**
* Handle the "Follow" Request
*
* @param array $object The JSON "Follow" Activity
* @param int $user_id The ID of the ID of the WordPress User
*
* @return void
*/
public static function handle_follow_request( $object, $user_id ) {
// save follower
$follower = self::add_follower( $user_id, $object['actor'] );
do_action( 'activitypub_followers_post_follow', $object['actor'], $object, $user_id, $follower );
}
/**
* Handle "Unfollow" requests
*
* @param array $object The JSON "Undo" Activity
* @param int $user_id The ID of the ID of the WordPress User
*/
public static function handle_undo_request( $object, $user_id ) {
if (
isset( $object['object'] ) &&
isset( $object['object']['type'] ) &&
'Follow' === $object['object']['type']
) {
self::remove_follower( $user_id, $object['actor'] );
}
}
/**
* Add new Follower
*
@ -243,54 +109,6 @@ class Followers {
return null;
}
/**
* Send Accept response
*
* @param string $actor The Actor URL
* @param array $object The Activity object
* @param int $user_id The ID of the WordPress User
* @param Activitypub\Model\Follower $follower The Follower object
*
* @return void
*/
public static function send_follow_response( $actor, $object, $user_id, $follower ) {
if ( is_wp_error( $follower ) ) {
// it is not even possible to send a "Reject" because
// we can not get the Remote-Inbox
return;
}
// only send minimal data
$object = array_intersect_key(
$object,
array_flip(
array(
'id',
'type',
'actor',
'object',
)
)
);
$user = Users::get_by_id( $user_id );
// get inbox
$inbox = $follower->get_shared_inbox();
// send "Accept" activity
$activity = new Activity();
$activity->set_type( 'Accept' );
$activity->set_object( $object );
$activity->set_actor( $user->get_id() );
$activity->set_to( $actor );
$activity->set_id( $user->get_id() . '#follow-' . \preg_replace( '~^https?://~', '', $actor ) . '-' . \time() );
$activity = $activity->to_json();
Http::post( $inbox, $activity, $user_id );
}
/**
* Get the Followers of a given user
*

View file

@ -0,0 +1,133 @@
<?php
namespace Activitypub\Collection;
use WP_Error;
use function Activitypub\object_id_to_comment;
use function Activitypub\get_remote_metadata_by_actor;
/**
* ActivityPub Interactions Collection
*/
class Interactions {
/**
* Add a comment to a post
*
* @param array $activity The activity-object
*
* @return array|false The commentdata or false on failure
*/
public static function add_comment( $activity ) {
if (
! isset( $activity['object'] ) ||
! isset( $activity['object']['id'] )
) {
return new WP_Error(
'activitypub_no_valid_object',
__( 'No object id found.', 'activitypub' ),
array( 'status' => 400 )
);
}
if ( ! isset( $activity['object']['inReplyTo'] ) ) {
return new WP_Error(
'activitypub_no_reply',
__( 'Object is no reply.', 'activitypub' ),
array( 'status' => 400 )
);
}
$in_reply_to = \esc_url_raw( $activity['object']['inReplyTo'] );
$comment_post_id = \url_to_postid( $in_reply_to );
$parent_comment = object_id_to_comment( $in_reply_to );
// save only replys and reactions
if ( ! $comment_post_id && $parent_comment ) {
$comment_post_id = $parent_comment->comment_post_ID;
}
// not a reply to a post or comment
if ( ! $comment_post_id ) {
return new WP_Error(
'activitypub_no_reply',
__( 'Object is no reply.', 'activitypub' ),
array( 'status' => 400 )
);
}
$meta = get_remote_metadata_by_actor( $activity['actor'] );
if ( ! $meta || \is_wp_error( $meta ) ) {
return new WP_Error(
'activitypub_invalid_follower',
__( 'Invalid Follower', 'activitypub' ),
array( 'status' => 400 )
);
}
$commentdata = array(
'comment_post_ID' => $comment_post_id,
'comment_author' => \esc_attr( $meta['name'] ),
'comment_author_url' => \esc_url_raw( $meta['url'] ),
'comment_content' => addslashes( \wp_kses( $activity['object']['content'], 'pre_comment_content' ) ),
'comment_type' => 'comment',
'comment_author_email' => '',
'comment_parent' => $parent_comment ? $parent_comment->comment_ID : 0,
'comment_meta' => array(
'source_id' => \esc_url_raw( $activity['object']['id'] ),
'source_url' => \esc_url_raw( $activity['object']['url'] ),
'avatar_url' => \esc_url_raw( $meta['icon']['url'] ),
'protocol' => 'activitypub',
),
);
// disable flood control
\remove_action( 'check_comment_flood', 'check_comment_flood_db', 10 );
// 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 );
$comment = \wp_new_comment( $commentdata, true );
\remove_filter( 'wp_kses_allowed_html', array( self::class, 'allowed_comment_html' ), 10 );
\remove_filter( 'pre_option_require_name_email', '__return_false' );
// re-add flood control
\add_action( 'check_comment_flood', 'check_comment_flood_db', 10, 4 );
return $comment;
}
/**
* Adds line breaks to the list of allowed comment tags.
*
* @param array $allowedtags Allowed HTML tags.
* @param string $context Context.
* @return array Filtered tag list.
*/
public static function allowed_comment_html( $allowedtags, $context = '' ) {
if ( 'pre_comment_content' !== $context ) {
// Do nothing.
return $allowedtags;
}
// Add `p` and `br` to the list of allowed tags.
if ( ! array_key_exists( 'br', $allowedtags ) ) {
$allowedtags['br'] = array();
}
if ( ! array_key_exists( 'p', $allowedtags ) ) {
$allowedtags['p'] = array();
}
return $allowedtags;
}
}

View file

@ -2,6 +2,7 @@
namespace Activitypub;
use WP_Error;
use WP_Comment_Query;
use Activitypub\Http;
use Activitypub\Activity\Activity;
use Activitypub\Collection\Followers;
@ -279,16 +280,6 @@ function is_activitypub_request() {
return false;
}
// Check if the current post type supports ActivityPub.
if ( \is_singular() ) {
$queried_object = \get_queried_object();
$post_type = \get_post_type( $queried_object );
if ( ! \post_type_supports( $post_type, 'activitypub' ) ) {
return false;
}
}
// One can trigger an ActivityPub request by adding ?activitypub to the URL.
// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.VariableRedeclaration
global $wp_query;
@ -486,6 +477,81 @@ function is_blog_public() {
return (bool) apply_filters( 'activitypub_is_blog_public', \get_option( 'blog_public', 1 ) );
}
/**
* Sanitize a URL
*
* @param string $value The URL to sanitize
*
* @return string|null The sanitized URL or null if invalid
*/
function sanitize_url( $value ) {
if ( filter_var( $value, FILTER_VALIDATE_URL ) === false ) {
return null;
}
return esc_url_raw( $value );
}
/**
* Extract recipient URLs from Activity object
*
* @param array $data
*
* @return array The list of user URLs
*/
function extract_recipients_from_activity( $data ) {
$recipient_items = array();
foreach ( array( 'to', 'bto', 'cc', 'bcc', 'audience' ) as $i ) {
if ( array_key_exists( $i, $data ) ) {
if ( is_array( $data[ $i ] ) ) {
$recipient = $data[ $i ];
} else {
$recipient = array( $data[ $i ] );
}
$recipient_items = array_merge( $recipient_items, $recipient );
}
if ( is_array( $data['object'] ) && array_key_exists( $i, $data['object'] ) ) {
if ( is_array( $data['object'][ $i ] ) ) {
$recipient = $data['object'][ $i ];
} else {
$recipient = array( $data['object'][ $i ] );
}
$recipient_items = array_merge( $recipient_items, $recipient );
}
}
$recipients = array();
// flatten array
foreach ( $recipient_items as $recipient ) {
if ( is_array( $recipient ) ) {
// check if recipient is an object
if ( array_key_exists( 'id', $recipient ) ) {
$recipients[] = $recipient['id'];
}
} else {
$recipients[] = $recipient;
}
}
return array_unique( $recipients );
}
/**
* Check if passed Activity is Public
*
* @param array $data The Activity object as array
*
* @return boolean True if public, false if not
*/
function is_activity_public( $data ) {
$recipients = extract_recipients_from_activity( $data );
return in_array( 'https://www.w3.org/ns/activitystreams#Public', $recipients, true );
}
/**
* Get active users based on a given duration
*
@ -557,3 +623,29 @@ function get_total_users() {
return $users + 1;
}
/**
* Examine a comment ID and look up an existing comment it represents.
*
* @param string $id ActivityPub object ID (usually a URL) to check.
*
* @return int|boolean Comment ID, or false on failure.
*/
function object_id_to_comment( $id ) {
$comment_query = new WP_Comment_Query(
array(
'meta_key' => 'source_id', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
'meta_value' => $id, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
)
);
if ( ! $comment_query->comments ) {
return false;
}
if ( count( $comment_query->comments ) > 1 ) {
return false;
}
return $comment_query->comments[0];
}

View file

@ -0,0 +1,73 @@
<?php
namespace Activitypub\Handler;
use WP_Error;
use Activitypub\Collection\Interactions;
use function Activitypub\is_activity_public;
use function Activitypub\object_id_to_comment;
/**
* Handle Create requests
*/
class Create {
/**
* Initialize the class, registering WordPress hooks
*/
public static function init() {
\add_action( 'activitypub_inbox_create', array( self::class, 'handle_create' ), 10, 3 );
}
/**
* Handles "Create" requests
*
* @param array $array The activity-object
* @param int $user_id The id of the local blog-user
* @param Activitypub\Activity $object The activity object
*
* @return void|WP_Error WP_Error on failure
*/
public static function handle_create( $array, $user_id, $object = null ) {
if (
! isset( $array['object'] ) ||
! isset( $array['object']['id'] )
) {
return new WP_Error(
'activitypub_no_valid_object',
__( 'No object id found.', 'activitypub' ),
array( 'status' => 400 )
);
}
// check if Activity is public or not
if ( ! is_activity_public( $array ) ) {
// @todo maybe send email
return new WP_Error(
'activitypub_activity_not_public',
__( 'Activity is not public.', 'activitypub' ),
array( 'status' => 400 )
);
}
$check_dupe = object_id_to_comment( $array['object']['id'] );
// if comment exists, call update action
if ( $check_dupe ) {
\do_action( 'activitypub_inbox_update', $array, $user_id, $object );
return new WP_Error(
'activitypub_comment_exists',
__( 'Comment already exists, initiated Update process.', 'activitypub' ),
array( 'status' => 400 )
);
}
$reaction = Interactions::add_comment( $array );
$state = null;
if ( $reaction ) {
$state = $reaction['comment_ID'];
}
\do_action( 'activitypub_handled_create', $array, $user_id, $state, $reaction );
}
}

View file

@ -0,0 +1,64 @@
<?php
namespace Activitypub\Handler;
use Activitypub\Collection\Followers;
/**
* Handles Delete requests.
*/
class Delete {
/**
* Initialize the class, registering WordPress hooks
*/
public static function init() {
\add_action( 'activitypub_inbox_delete', array( self::class, 'handle_delete' ), 10, 2 );
//
}
/**
* Handles "Delete" requests.
*
* @param array $activity The delete activity.
* @param int $user_id The ID of the user performing the delete activity.
*/
public function handle_delete( $activity, $user_id ) {
if (
! isset( $activity['object'] ) ||
! is_array( $activity['object'] ) ||
! isset( $activity['object']['id'] )
) {
return;
}
$object_type = isset( $activity['object']['type'] ) ? $activity['object']['type'] : '';
switch ( $object_type ) {
case 'Person':
case 'Group':
case 'Organization':
case 'Service':
case 'Application':
$follower = Followers::get_follower( $user_id, $activity['actor'] );
if ( $follower ) {
$follower->delete();
}
// delete all activities from this user.
break;
case 'Tombstone':
// Handle tombstone.
break;
case 'Note':
case 'Article':
case 'Image':
case 'Audio':
case 'Video':
case 'Event':
case 'Document':
default:
// Handle delete activity for other object types.
break;
}
}
}

View file

@ -0,0 +1,81 @@
<?php
namespace Activitypub\Handler;
use Activitypub\Http;
use Activitypub\Collection\Users;
use Activitypub\Activity\Activity;
use Activitypub\Collection\Followers;
/**
* Handle Follow requests
*/
class Follow {
/**
* Initialize the class, registering WordPress hooks
*/
public static function init() {
\add_action( 'activitypub_inbox_follow', array( self::class, 'handle_follow_request' ), 10, 2 );
\add_action( 'activitypub_followers_post_follow', array( self::class, 'send_follow_response' ), 10, 4 );
}
/**
* Handle "Follow" requests
*
* @param array $activity The activity object
* @param int $user_id The user ID
*/
public function handle_follow( $activity, $user_id ) {
// save follower
$follower = Followers::add_follower( $user_id, $activity['actor'] );
do_action( 'activitypub_followers_post_follow', $activity['actor'], $activity, $user_id, $follower );
}
/**
* Send Accept response
*
* @param string $actor The Actor URL
* @param array $object The Activity object
* @param int $user_id The ID of the WordPress User
* @param Activitypub\Model\Follower $follower The Follower object
*
* @return void
*/
public static function send_follow_response( $actor, $object, $user_id, $follower ) {
if ( \is_wp_error( $follower ) ) {
// it is not even possible to send a "Reject" because
// we can not get the Remote-Inbox
return;
}
// only send minimal data
$object = array_intersect_key(
$object,
array_flip(
array(
'id',
'type',
'actor',
'object',
)
)
);
$user = Users::get_by_id( $user_id );
// get inbox
$inbox = $follower->get_shared_inbox();
// send "Accept" activity
$activity = new Activity();
$activity->set_type( 'Accept' );
$activity->set_object( $object );
$activity->set_actor( $user->get_id() );
$activity->set_to( $actor );
$activity->set_id( $user->get_id() . '#follow-' . \preg_replace( '~^https?://~', '', $actor ) . '-' . \time() );
$activity = $activity->to_json();
Http::post( $inbox, $activity, $user_id );
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace Activitypub\Handler;
use Activitypub\Collection\Followers;
/**
* Handle Undo requests
*/
class Undo {
/**
* Initialize the class, registering WordPress hooks
*/
public static function init() {
\add_action( 'activitypub_inbox_undo', array( self::class, 'handle_undo' ), 10, 2 );
}
/**
* Handle "Unfollow" requests
*
* @param array $activity The JSON "Undo" Activity
* @param int $user_id The ID of the ID of the WordPress User
*/
public static function handle_undo( $activity, $user_id ) {
if (
isset( $activity['object'] ) &&
isset( $activity['actor'] ) &&
isset( $activity['object']['type'] ) &&
'Follow' === $activity['object']['type']
) {
Followers::remove_follower( $user_id, $activity['actor'] );
}
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace Activitypub\Handler;
use WP_Error;
use WP_REST_Request;
use WP_REST_Response;
/**
* Handle Update requests.
*/
class Update {
/**
* Initialize the class, registering WordPress hooks
*/
public static function init() {
\add_action( 'activitypub_inbox_update', array( self::class, 'handle_update' ), 10 );
}
/**
* Handle "Update" requests
*
* @param array $activity The JSON "Undo" Activity
*/
public static function handle_update( $activity ) {
// Get the post object.
$post = null;
// Check if the post exists.
if ( ! $post ) {
return new WP_Error( 'activitypub_post_not_found', __( 'Post not found.', 'activitypub' ), array( 'status' => 404 ) );
}
// Check if the user has permission to edit the post.
if ( ! \current_user_can( 'edit_post', $post->ID ) ) {
return new WP_Error( 'activitypub_permission_denied', __( 'You do not have permission to edit this post.', 'activitypub' ), array( 'status' => 403 ) );
}
// Update the post content.
$post_data = array(
'ID' => $post->ID,
'post_content' => $activity['object']['content'],
);
wp_update_post( $post_data );
}
}

View file

@ -315,7 +315,7 @@ class Follower extends Actor {
$object->set_id( $post->guid );
$object->set_name( $post->post_title );
$object->set_summary( $post->post_excerpt );
$object->set_published( gmdate( 'Y-m-d H:i:s', strtotime( $post->post_date ) ) );
$object->set_published( gmdate( 'Y-m-d H:i:s', strtotime( $post->post_published ) ) );
$object->set_updated( gmdate( 'Y-m-d H:i:s', strtotime( $post->post_modified ) ) );
return $object;

View file

@ -1,7 +1,7 @@
<?php
namespace Activitypub\Model;
use Activitypub\Transformer\Post as Transformer_Post;
use Activitypub\Transformer\Post as Post_Transformer;
/**
* ActivityPub Post Class
@ -33,9 +33,8 @@ class Post {
public function __construct( $post, $post_author = null ) {
_deprecated_function( __CLASS__, '1.0.0', '\Activitypub\Transformer\Post' );
$this->post = $post;
$transformer = new Transformer_Post();
$this->object = $transformer->set_wp_post( $post )->to_object();
$this->post = $post;
$this->object = Post_Transformer::transform( $post )->to_object();
}
/**

View file

@ -4,7 +4,7 @@ namespace Activitypub\Rest;
use WP_Error;
use WP_REST_Server;
use WP_REST_Response;
use Activitypub\Transformer\Transformers_Manager;
use Activitypub\Transformer\Post;
use Activitypub\Activity\Activity;
use Activitypub\Collection\Users as User_Collection;
@ -168,7 +168,7 @@ class Collection {
);
foreach ( $posts as $post ) {
$response['orderedItems'][] = Transformers_Manager::instance()->get_transformer( $post )->to_object()->to_array();
$response['orderedItems'][] = Post::transform( $post )->to_object()->to_array();
}
$rest_response = new WP_REST_Response( $response, 200 );

View file

@ -11,6 +11,7 @@ use function Activitypub\get_context;
use function Activitypub\url_to_authorid;
use function Activitypub\get_rest_url_by_path;
use function Activitypub\get_remote_metadata_by_actor;
use function Activitypub\extract_recipients_from_activity;
/**
* ActivityPub Inbox REST-Class
@ -130,12 +131,13 @@ class Inbox {
return $user;
}
$data = $request->get_json_params();
$type = $request->get_param( 'type' );
$type = \strtolower( $type );
$data = $request->get_json_params();
$activity = Activity::init_from_array( $data );
$type = $request->get_param( 'type' );
$type = \strtolower( $type );
\do_action( 'activitypub_inbox', $data, $user->get__id(), $type );
\do_action( "activitypub_inbox_{$type}", $data, $user->get__id() );
\do_action( 'activitypub_inbox', $data, $user->get__id(), $type, $activity );
\do_action( "activitypub_inbox_{$type}", $data, $user->get__id(), $activity );
$rest_response = new WP_REST_Response( array(), 202 );
$rest_response->header( 'Content-Type', 'application/activity+json; charset=' . get_option( 'blog_charset' ) );
@ -151,9 +153,10 @@ class Inbox {
* @return WP_REST_Response
*/
public static function shared_inbox_post( $request ) {
$data = $request->get_json_params();
$type = $request->get_param( 'type' );
$users = self::extract_recipients( $data );
$data = $request->get_json_params();
$activity = Activity::init_from_array( $data );
$type = $request->get_param( 'type' );
$users = self::get_recipients( $data );
if ( ! $users ) {
return new WP_Error(
@ -181,8 +184,8 @@ class Inbox {
$type = \strtolower( $type );
\do_action( 'activitypub_inbox', $data, $user->ID, $type );
\do_action( "activitypub_inbox_{$type}", $data, $user->ID );
\do_action( 'activitypub_inbox', $data, $user->ID, $type, $activity );
\do_action( "activitypub_inbox_{$type}", $data, $user->ID, $activity );
}
$rest_response = new WP_REST_Response( array(), 202 );
@ -236,12 +239,8 @@ class Inbox {
$params['actor'] = array(
'required' => true,
'sanitize_callback' => function( $param, $request, $key ) {
if ( \is_array( $param ) ) {
if ( isset( $param['id'] ) ) {
$param = $param['id'];
} else {
$param = $param['url'];
}
if ( ! \is_string( $param ) ) {
$param = $param['id'];
}
return \esc_url_raw( $param );
},
@ -340,121 +339,6 @@ class Inbox {
return $params;
}
/**
* Handles "Create" requests
*
* @param array $object The activity-object
* @param int $user_id The id of the local blog-user
*/
public static function handle_create( $object, $user_id ) {
$meta = get_remote_metadata_by_actor( $object['actor'] );
if ( ! isset( $object['object']['inReplyTo'] ) ) {
return;
}
// check if Activity is public or not
if ( ! self::is_activity_public( $object ) ) {
// @todo maybe send email
return;
}
$comment_post_id = \url_to_postid( $object['object']['inReplyTo'] );
// save only replys and reactions
if ( ! $comment_post_id ) {
return false;
}
$commentdata = array(
'comment_post_ID' => $comment_post_id,
'comment_author' => \esc_attr( $meta['name'] ),
'comment_author_url' => \esc_url_raw( $object['actor'] ),
'comment_content' => addslashes( \wp_kses( $object['object']['content'], 'pre_comment_content' ) ),
'comment_type' => 'comment',
'comment_author_email' => '',
'comment_parent' => 0,
'comment_meta' => array(
'source_url' => \esc_url_raw( $object['object']['url'] ),
'avatar_url' => \esc_url_raw( $meta['icon']['url'] ),
'protocol' => 'activitypub',
),
);
// disable flood control
\remove_action( 'check_comment_flood', 'check_comment_flood_db', 10 );
// 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 );
$state = \wp_new_comment( $commentdata, true );
\remove_filter( 'wp_kses_allowed_html', array( self::class, 'allowed_comment_html' ) );
\remove_filter( 'pre_option_require_name_email', '__return_false' );
// re-add flood control
\add_action( 'check_comment_flood', 'check_comment_flood_db', 10, 4 );
do_action( 'activitypub_handled_create', $object, $user_id, $state, $commentdata );
}
/**
* Extract recipient URLs from Activity object
*
* @param array $data
*
* @return array The list of user URLs
*/
public static function extract_recipients( $data ) {
$recipient_items = array();
foreach ( array( 'to', 'bto', 'cc', 'bcc', 'audience' ) as $i ) {
if ( array_key_exists( $i, $data ) ) {
if ( is_array( $data[ $i ] ) ) {
$recipient = $data[ $i ];
} else {
$recipient = array( $data[ $i ] );
}
$recipient_items = array_merge( $recipient_items, $recipient );
}
if ( is_array( $data['object'] ) && array_key_exists( $i, $data['object'] ) ) {
if ( is_array( $data['object'][ $i ] ) ) {
$recipient = $data['object'][ $i ];
} else {
$recipient = array( $data['object'][ $i ] );
}
$recipient_items = array_merge( $recipient_items, $recipient );
}
}
$recipients = array();
// flatten array
foreach ( $recipient_items as $recipient ) {
if ( is_array( $recipient ) ) {
// check if recipient is an object
if ( array_key_exists( 'id', $recipient ) ) {
$recipients[] = $recipient['id'];
}
} else {
$recipients[] = $recipient;
}
}
return array_unique( $recipients );
}
/**
* Get local user recipients
*
@ -463,7 +347,7 @@ class Inbox {
* @return array The list of local users
*/
public static function get_recipients( $data ) {
$recipients = self::extract_recipients( $data );
$recipients = extract_recipients_from_activity( $data );
$users = array();
foreach ( $recipients as $recipient ) {
@ -478,41 +362,4 @@ class Inbox {
return $users;
}
/**
* Check if passed Activity is Public
*
* @param array $data
* @return boolean
*/
public static function is_activity_public( $data ) {
$recipients = self::extract_recipients( $data );
return in_array( 'https://www.w3.org/ns/activitystreams#Public', $recipients, true );
}
/**
* Adds line breaks to the list of allowed comment tags.
*
* @param array $allowedtags Allowed HTML tags.
* @param string $context Context.
* @return array Filtered tag list.
*/
public static function allowed_comment_html( $allowedtags, $context = '' ) {
if ( 'pre_comment_content' !== $context ) {
// Do nothing.
return $allowedtags;
}
// Add `p` and `br` to the list of allowed tags.
if ( ! array_key_exists( 'br', $allowedtags ) ) {
$allowedtags['br'] = array();
}
if ( ! array_key_exists( 'p', $allowedtags ) ) {
$allowedtags['p'] = array();
}
return $allowedtags;
}
}

View file

@ -5,7 +5,7 @@ use stdClass;
use WP_Error;
use WP_REST_Server;
use WP_REST_Response;
use Activitypub\Transformer\Transformers_Manager;
use Activitypub\Transformer\Post;
use Activitypub\Activity\Activity;
use Activitypub\Collection\Users as User_Collection;
@ -59,7 +59,7 @@ class Outbox {
return $user;
}
$post_types = array_keys( \get_option( 'activitypub_transformer_mapping', array( 'post' => 'activitypub/default', 'page' => 'activitypub/default' ) ) );
$post_types = \get_option( 'activitypub_support_post_types', array( 'post', 'page' ) );
$page = $request->get_param( 'page', 1 );
@ -105,8 +105,7 @@ class Outbox {
);
foreach ( $posts as $post ) {
$transformer = \Activitypub\Transformer\Transformers_Manager::instance()->get_transformer( $post );
$post = $transformer->to_object();
$post = Post::transform( $post )->to_object();
$activity = new Activity();
$activity->set_type( 'Create' );
$activity->set_context( null );

View file

@ -30,24 +30,19 @@ class Followers extends WP_List_Table {
public function get_columns() {
return array(
'cb' => '<input type="checkbox" />',
'avatar' => \__( 'Avatar', 'activitypub' ),
'post_title' => \__( 'Name', 'activitypub' ),
'username' => \__( 'Username', 'activitypub' ),
'url' => \__( 'URL', 'activitypub' ),
'published' => \__( 'Followed', 'activitypub' ),
'modified' => \__( 'Last updated', 'activitypub' ),
'cb' => '<input type="checkbox" />',
'avatar' => \__( 'Avatar', 'activitypub' ),
'name' => \__( 'Name', 'activitypub' ),
'username' => \__( 'Username', 'activitypub' ),
'url' => \__( 'URL', 'activitypub' ),
'updated' => \__( 'Last updated', 'activitypub' ),
//'errors' => \__( 'Errors', 'activitypub' ),
//'latest-error' => \__( 'Latest Error Message', 'activitypub' ),
);
}
public function get_sortable_columns() {
$sortable_columns = array(
'post_title' => array( 'post_title', true ),
'modified' => array( 'modified', false ),
'published' => array( 'published', false ),
);
return $sortable_columns;
return array();
}
public function prepare_items() {
@ -60,32 +55,8 @@ class Followers extends WP_List_Table {
$page_num = $this->get_pagenum();
$per_page = 20;
$args = array();
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['orderby'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$args['orderby'] = sanitize_text_field( wp_unslash( $_GET['orderby'] ) );
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['order'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$args['order'] = sanitize_text_field( wp_unslash( $_GET['order'] ) );
}
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( isset( $_GET['s'] ) && isset( $_REQUEST['_wpnonce'] ) ) {
$nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );
if ( wp_verify_nonce( $nonce, 'bulk-' . $this->_args['plural'] ) ) {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$args['s'] = sanitize_text_field( wp_unslash( $_GET['s'] ) );
}
}
$followers_with_count = FollowerCollection::get_followers_with_count( $this->user_id, $per_page, $page_num, $args );
$followers = $followers_with_count['followers'];
$counter = $followers_with_count['total'];
$followers = FollowerCollection::get_followers( $this->user_id, $per_page, $page_num );
$counter = FollowerCollection::count_followers( $this->user_id );
$this->items = array();
$this->set_pagination_args(
@ -98,13 +69,14 @@ class Followers extends WP_List_Table {
foreach ( $followers as $follower ) {
$item = array(
'icon' => esc_attr( $follower->get_icon_url() ),
'post_title' => esc_attr( $follower->get_name() ),
'username' => esc_attr( $follower->get_preferred_username() ),
'url' => esc_attr( $follower->get_url() ),
'identifier' => esc_attr( $follower->get_id() ),
'published' => esc_attr( $follower->get_published() ),
'modified' => esc_attr( $follower->get_updated() ),
'icon' => esc_attr( $follower->get_icon_url() ),
'name' => esc_attr( $follower->get_name() ),
'username' => esc_attr( $follower->get_preferred_username() ),
'url' => esc_attr( $follower->get_url() ),
'identifier' => esc_attr( $follower->get_id() ),
'updated' => esc_attr( $follower->get_updated() ),
'errors' => $follower->count_errors(),
'latest-error' => $follower->get_latest_error_message(),
);
$this->items[] = $item;
@ -144,11 +116,11 @@ class Followers extends WP_List_Table {
}
public function process_action() {
if ( ! isset( $_REQUEST['followers'] ) || ! isset( $_REQUEST['_wpnonce'] ) ) {
if ( ! isset( $_REQUEST['followers'] ) || ! isset( $_REQUEST['_apnonce'] ) ) {
return false;
}
$nonce = sanitize_text_field( wp_unslash( $_REQUEST['_wpnonce'] ) );
if ( ! wp_verify_nonce( $nonce, 'bulk-' . $this->_args['plural'] ) ) {
$nonce = sanitize_text_field( wp_unslash( $_REQUEST['_apnonce'] ) );
if ( ! wp_verify_nonce( $nonce, 'activitypub-followers-list' ) ) {
return false;
}

View file

@ -1,619 +0,0 @@
<?php
/**
* Inspired by the PHP ActivityPub Library by @Landrok
*
* @link https://github.com/landrok/activitypub
*/
namespace Activitypub\Transformer;
use WP_Post;
use Activitypub\Collection\Users;
use Activitypub\Model\Blog_User;
use Activitypub\Activity\Base_Object;
use Activitypub\Shortcodes;
use function Activitypub\esc_hashtag;
use function Activitypub\is_single_user;
use function Activitypub\get_rest_url_by_path;
use function Activitypub\site_supports_blocks;
/**
* Base class to implement WordPress to ActivityPub transformers.
*/
abstract class Base {
/**
* The WP_Post object.
*
* @var WP_Post
*/
protected $wp_post;
/**
* Assign WP_Post Object to a specific transformer instance.
*
* This helps to chain the output of the Transformer.
*
* @param WP_Post $wp_post The WP_Post object.
* @return void
*/
public function set_wp_post( WP_Post $wp_post ) {
$post_type = get_post_type( $wp_post );
if ( ! $this->supports_post_type( $post_type ) ) {
_doing_it_wrong(
__METHOD__,
/* translators: %s: Block name. */
sprintf( 'The Transformer "%s" does not support the post type "%s".', esc_html( $this->get_label() ), esc_html( $post_type ) ),
'version_number_transformer_management_placeholder'
);
}
$this->wp_post = $wp_post;
}
/**
* Get the supported WP post types that the transformer can use as an input.
*
* By default all post types are supported.
* You may very likely wish to override this function.
*
* @since version_number_transformer_management_placeholder
* @return string[] An array containing all the supported post types.
*/
public function get_supported_post_types() {
return \get_post_types( array( 'public' => true ), 'names' );
}
/**
* Get the name of the plugin that registered the transformer.
*
* @see Forked from the WordPress elementor plugin.
* @since version_number_transformer_management_placeholder
* @return string Plugin name
*/
private function get_plugin_name_from_transformer_instance( $transformer ) {
$class_reflection = new \ReflectionClass( $transformer );
$plugin_basename = plugin_basename( $class_reflection->getFileName() );
$plugin_directory = strtok( $plugin_basename, '/' );
$plugins_data = get_plugins( '/' . $plugin_directory );
$plugin_data = array_shift( $plugins_data );
if ( isset( $plugin_data['Name'] ) ) {
return $plugin_data['Name'];
} else {
return esc_html__( 'Unknown', 'activitypub' );
}
}
/**
* Return whether the transformer supports a post type.
*
* @since version_number_transformer_management_placeholder
* @return string post_type Post type name.
*/
final public function supports_post_type( $post_type ) {
return in_array( $post_type, $this->get_supported_post_types(), true );
}
/**
* Get the name used for registering the transformer with the ActivityPub plugin.
*
* @since version_number_transformer_management_placeholder
* @return string name
*/
abstract public function get_name();
/**
* Get the display name for the ActivityPub transformer.
*
* @since version_number_transformer_management_placeholder
* @return string display name
*/
abstract public function get_label();
/**
* Returns the ActivityStreams 2.0 Object-Type for a Post.
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#activity-types
*
* @return string The Object-Type.
*/
abstract protected function get_object_type();
/**
* Returns the content for the ActivityPub Item.
*
* The content will be generated based on the user settings.
*
* @return string The content.
*/
protected function get_content() {
global $post;
/**
* Provides an action hook so plugins can add their own hooks/filters before AP content is generated.
*
* Example: if a plugin adds a filter to `the_content` to add a button to the end of posts, it can also remove that filter here.
*
* @param WP_Post $post The post object.
*/
do_action( 'activitypub_before_get_content', $post );
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$post = $this->wp_post;
$content = $this->get_post_content_template();
// Register our shortcodes just in time.
Shortcodes::register();
// Fill in the shortcodes.
setup_postdata( $post );
$content = do_shortcode( $content );
wp_reset_postdata();
$content = \wpautop( $content );
$content = \preg_replace( '/[\n\r\t]/', '', $content );
$content = \trim( $content );
$content = \apply_filters( 'activitypub_the_content', $content, $post );
// Don't need these any more, should never appear in a post.
Shortcodes::unregister();
return $content;
}
/**
* Gets the template to use to generate the content of the activitypub item.
*
* @return string The Template.
*/
protected function get_post_content_template() {
if ( 'excerpt' === \get_option( 'activitypub_post_content_type', 'content' ) ) {
return "[ap_excerpt]\n\n[ap_permalink type=\"html\"]";
}
if ( 'title' === \get_option( 'activitypub_post_content_type', 'content' ) ) {
return "[ap_title]\n\n[ap_permalink type=\"html\"]";
}
if ( 'content' === \get_option( 'activitypub_post_content_type', 'content' ) ) {
return "[ap_content]\n\n[ap_permalink type=\"html\"]\n\n[ap_hashtags]";
}
return \get_option( 'activitypub_custom_post_content', ACTIVITYPUB_CUSTOM_POST_CONTENT );
}
/**
* Returns the ID of the Post.
*
* @return string The Posts ID.
*/
public function get_id() {
return $this->get_url();
}
/**
* Returns the URL of the Post.
*
* @return string The Posts URL.
*/
public function get_url() {
$post = $this->wp_post;
if ( 'trash' === get_post_status( $post ) ) {
$permalink = \get_post_meta( $post->ID, 'activitypub_canonical_url', true );
} else {
$permalink = \get_permalink( $post );
}
return \esc_url( $permalink );
}
/**
* Returns the User-URL of the Author of the Post.
*
* If `single_user` mode is enabled, the URL of the Blog-User is returned.
*
* @return string The User-URL.
*/
protected function get_attributed_to() {
if ( is_single_user() ) {
$user = new Blog_User();
return $user->get_url();
}
return Users::get_by_id( $this->wp_post->post_author )->get_url();
}
/**
* Generates all Media Attachments for a Post.
*
* @return array The Attachments.
*/
protected function get_attachments() {
// Once upon a time we only supported images, but we now support audio/video as well.
// We maintain the image-centric naming for backwards compatibility.
$max_media = intval( \apply_filters( 'activitypub_max_image_attachments', \get_option( 'activitypub_max_image_attachments', ACTIVITYPUB_MAX_IMAGE_ATTACHMENTS ) ) );
if ( site_supports_blocks() && \has_blocks( $this->wp_post->post_content ) ) {
return $this->get_block_attachments( $max_media );
}
return $this->get_classic_editor_images( $max_media );
}
/**
* Get media attachments from blocks. They will be formatted as ActivityPub attachments, not as WP attachments.
*
* @param int $max_media The maximum number of attachments to return.
*
* @return array The attachments.
*/
protected function get_block_attachments( $max_media ) {
// max media can't be negative or zero
if ( $max_media <= 0 ) {
return array();
}
$id = $this->wp_post->ID;
$media_ids = array();
// list post thumbnail first if this post has one
if ( \function_exists( 'has_post_thumbnail' ) && \has_post_thumbnail( $id ) ) {
$media_ids[] = \get_post_thumbnail_id( $id );
}
if ( $max_media > 0 ) {
$blocks = \parse_blocks( $this->wp_post->post_content );
$media_ids = self::get_media_ids_from_blocks( $blocks, $media_ids, $max_media );
}
return \array_filter( \array_map( array( self::class, 'wp_attachment_to_activity_attachment' ), $media_ids ) );
}
/**
* Get image attachments from the classic editor.
* Note that audio/video attachments are only supported in the block editor.
*
* @param int $max_images The maximum number of images to return.
*
* @return array The attachments.
*/
protected function get_classic_editor_images( $max_images ) {
// max images can't be negative or zero
if ( $max_images <= 0 ) {
return array();
}
$id = $this->wp_post->ID;
$image_ids = array();
// list post thumbnail first if this post has one
if ( \function_exists( 'has_post_thumbnail' ) && \has_post_thumbnail( $id ) ) {
$image_ids[] = \get_post_thumbnail_id( $id );
--$max_images;
}
if ( $max_images > 0 ) {
$query = new \WP_Query(
array(
'post_parent' => $id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'posts_per_page' => $max_images,
)
);
foreach ( $query->get_posts() as $attachment ) {
if ( ! \in_array( $attachment->ID, $image_ids, true ) ) {
$image_ids[] = $attachment->ID;
}
}
}
$image_ids = \array_unique( $image_ids );
return \array_filter( \array_map( array( self::class, 'wp_attachment_to_activity_attachment' ), $image_ids ) );
}
/**
* Recursively get media IDs from blocks.
*
* @param array $blocks The blocks to search for media IDs
* @param array $media_ids The media IDs to append new IDs to
* @param int $max_media The maximum number of media to return.
*
* @return array The image IDs.
*/
protected static function get_media_ids_from_blocks( $blocks, $media_ids, $max_media ) {
foreach ( $blocks as $block ) {
// recurse into inner blocks
if ( ! empty( $block['innerBlocks'] ) ) {
$media_ids = self::get_media_ids_from_blocks( $block['innerBlocks'], $media_ids, $max_media );
}
switch ( $block['blockName'] ) {
case 'core/image':
case 'core/cover':
case 'core/audio':
case 'core/video':
case 'videopress/video':
if ( ! empty( $block['attrs']['id'] ) ) {
$media_ids[] = $block['attrs']['id'];
}
break;
case 'jetpack/slideshow':
case 'jetpack/tiled-gallery':
if ( ! empty( $block['attrs']['ids'] ) ) {
$media_ids = array_merge( $media_ids, $block['attrs']['ids'] );
}
break;
case 'jetpack/image-compare':
if ( ! empty( $block['attrs']['beforeImageId'] ) ) {
$media_ids[] = $block['attrs']['beforeImageId'];
}
if ( ! empty( $block['attrs']['afterImageId'] ) ) {
$media_ids[] = $block['attrs']['afterImageId'];
}
break;
}
// depupe
$media_ids = \array_unique( $media_ids );
// stop doing unneeded work
if ( count( $media_ids ) >= $max_media ) {
break;
}
}
// still need to slice it because one gallery could knock us over the limit
return array_slice( $media_ids, 0, $max_media );
}
/**
* Converts a WordPress Attachment to an ActivityPub Attachment.
*
* @param int $id The Attachment ID.
*
* @return array The ActivityPub Attachment.
*/
public static function wp_attachment_to_activity_attachment( $id ) {
$attachment = array();
$mime_type = \get_post_mime_type( $id );
$mime_type_parts = \explode( '/', $mime_type );
// switching on image/audio/video
switch ( $mime_type_parts[0] ) {
case 'image':
$image_size = 'full';
/**
* Filter the image URL returned for each post.
*
* @param array|false $thumbnail The image URL, or false if no image is available.
* @param int $id The attachment ID.
* @param string $image_size The image size to retrieve. Set to 'full' by default.
*/
$thumbnail = apply_filters(
'activitypub_get_image',
self::get_image( $id, $image_size ),
$id,
$image_size
);
if ( $thumbnail ) {
$alt = \get_post_meta( $id, '_wp_attachment_image_alt', true );
$image = array(
'type' => 'Image',
'url' => $thumbnail[0],
'mediaType' => $mime_type,
);
if ( $alt ) {
$image['name'] = $alt;
}
$attachment = $image;
}
break;
case 'audio':
case 'video':
$attachment = array(
'type' => 'Document',
'mediaType' => $mime_type,
'url' => \wp_get_attachment_url( $id ),
'name' => \get_the_title( $id ),
);
$meta = wp_get_attachment_metadata( $id );
// height and width for videos
if ( isset( $meta['width'] ) && isset( $meta['height'] ) ) {
$attachment['width'] = $meta['width'];
$attachment['height'] = $meta['height'];
}
// @todo: add `icon` support for audio/video attachments. Maybe use post thumbnail?
break;
}
return \apply_filters( 'activitypub_attachment', $attachment, $id );
}
/**
* Return details about an image attachment.
*
* @param int $id The attachment ID.
* @param string $image_size The image size to retrieve. Set to 'full' by default.
*
* @return array|false Array of image data, or boolean false if no image is available.
*/
protected static function get_image( $id, $image_size = 'full' ) {
/**
* Hook into the image retrieval process. Before image retrieval.
*
* @param int $id The attachment ID.
* @param string $image_size The image size to retrieve. Set to 'full' by default.
*/
do_action( 'activitypub_get_image_pre', $id, $image_size );
$image = \wp_get_attachment_image_src( $id, $image_size );
/**
* Hook into the image retrieval process. After image retrieval.
*
* @param int $id The attachment ID.
* @param string $image_size The image size to retrieve. Set to 'full' by default.
*/
do_action( 'activitypub_get_image_post', $id, $image_size );
return $image;
}
/**
* Helper function to get the @-Mentions from the post content.
*
* @return array The list of @-Mentions.
*/
protected function get_mentions() {
return apply_filters( 'activitypub_extract_mentions', array(), $this->wp_post->post_content, $this->wp_post );
}
/**
* Returns a list of Mentions, used in the Post.
*
* @see https://docs.joinmastodon.org/spec/activitypub/#Mention
*
* @return array The list of Mentions.
*/
protected function get_cc() {
$cc = array();
$mentions = $this->get_mentions();
if ( $mentions ) {
foreach ( $mentions as $url ) {
$cc[] = $url;
}
}
return $cc;
}
/**
* Returns a list of Tags, used in the Post.
*
* This includes Hash-Tags and Mentions.
*
* @return array The list of Tags.
*/
protected function get_tags() {
$tags = array();
$post_tags = \get_the_tags( $this->wp_post->ID );
if ( $post_tags ) {
foreach ( $post_tags as $post_tag ) {
$tag = array(
'type' => 'Hashtag',
'href' => \esc_url( \get_tag_link( $post_tag->term_id ) ),
'name' => esc_hashtag( $post_tag->name ),
);
$tags[] = $tag;
}
}
$mentions = $this->get_mentions();
if ( $mentions ) {
foreach ( $mentions as $mention => $url ) {
$tag = array(
'type' => 'Mention',
'href' => \esc_url( $url ),
'name' => \esc_html( $mention ),
);
$tags[] = $tag;
}
}
return $tags;
}
/**
* Returns the locale of the post.
*
* @return string The locale of the post.
*/
public function get_locale() {
$post_id = $this->wp_post->ID;
$lang = \strtolower( \strtok( \get_locale(), '_-' ) );
/**
* Filter the locale of the post.
*
* @param string $lang The locale of the post.
* @param int $post_id The post ID.
* @param WP_Post $post The post object.
*
* @return string The filtered locale of the post.
*/
return apply_filters( 'activitypub_post_locale', $lang, $post_id, $this->wp_post );
}
/**
* Gets the contentMap
*
* @see https://www.w3.org/TR/activitystreams-vocabulary/#dfn-contentmap
*
* @return array the contenmap
*/
protected function get_content_map() {
return array(
$this->get_locale() => $this->get_content(),
);
}
/**
* Transforms the WP_Post object to an ActivityPub Object
*
* @see \Activitypub\Activity\Base_Object
*
* @return \Activitypub\Activity\Base_Object The ActivityPub Object
*/
public function to_object() {
$wp_post = $this->wp_post;
$object = new Base_Object();
$object->set_id( $this->get_id() );
$object->set_url( $this->get_url() );
$object->set_type( $this->get_object_type() );
$published = \strtotime( $wp_post->post_date_gmt );
$object->set_published( \gmdate( 'Y-m-d\TH:i:s\Z', $published ) );
$updated = \strtotime( $wp_post->post_modified_gmt );
if ( $updated > $published ) {
$object->set_updated( \gmdate( 'Y-m-d\TH:i:s\Z', $updated ) );
}
$object->set_attributed_to( $this->get_attributed_to() );
$object->set_content( $this->get_content() );
$object->set_content_map( $this->get_content_map );
$path = sprintf( 'users/%d/followers', intval( $wp_post->post_author ) );
$object->set_to(
array(
'https://www.w3.org/ns/activitystreams#Public',
get_rest_url_by_path( $path ),
)
);
$object->set_cc( $this->get_cc() );
$object->set_attachment( $this->get_attachments() );
$object->set_tag( $this->get_tags() );
return $object;
}
}

View file

@ -6,7 +6,6 @@ use Activitypub\Collection\Users;
use Activitypub\Model\Blog_User;
use Activitypub\Activity\Base_Object;
use Activitypub\Shortcodes;
use Activitypub\Transformer\Base;
use function Activitypub\esc_hashtag;
use function Activitypub\is_single_user;
@ -15,29 +14,375 @@ use function Activitypub\site_supports_blocks;
/**
* WordPress Post Transformer
*
* The Post Transformer is responsible for transforming a WP_Post object into different othe
* Object-Types.
*
* Currently supported are:
*
* - Activitypub\Activity\Base_Object
*/
class Post extends Base {
class Post {
/**
* Getter function for the name of the transformer.
* The WP_Post object.
*
* @return string name
* @var WP_Post
*/
public function get_name() {
return 'activitypub/default';
protected $wp_post;
/**
* Static function to Transform a WP_Post Object.
*
* This helps to chain the output of the Transformer.
*
* @param WP_Post $wp_post The WP_Post object
*
* @return void
*/
public static function transform( WP_Post $wp_post ) {
return new static( $wp_post );
}
/**
* Getter function for the display name (label/title) of the transformer.
*
* @return string name
*
* @param WP_Post $wp_post
*/
public function get_label() {
return 'Built-In';
public function __construct( WP_Post $wp_post ) {
$this->wp_post = $wp_post;
}
/**
* Transforms the WP_Post object to an ActivityPub Object
*
* @see \Activitypub\Activity\Base_Object
*
* @return \Activitypub\Activity\Base_Object The ActivityPub Object
*/
public function to_object() {
$wp_post = $this->wp_post;
$object = new Base_Object();
$object->set_id( $this->get_id() );
$object->set_url( $this->get_url() );
$object->set_type( $this->get_object_type() );
$published = \strtotime( $wp_post->post_date_gmt );
$object->set_published( \gmdate( 'Y-m-d\TH:i:s\Z', $published ) );
$updated = \strtotime( $wp_post->post_modified_gmt );
if ( $updated > $published ) {
$object->set_updated( \gmdate( 'Y-m-d\TH:i:s\Z', $updated ) );
}
$object->set_attributed_to( $this->get_attributed_to() );
$object->set_content( $this->get_content() );
$object->set_content_map(
array(
$this->get_locale() => $this->get_content(),
)
);
$path = sprintf( 'users/%d/followers', intval( $wp_post->post_author ) );
$object->set_to(
array(
'https://www.w3.org/ns/activitystreams#Public',
get_rest_url_by_path( $path ),
)
);
$object->set_cc( $this->get_cc() );
$object->set_attachment( $this->get_attachments() );
$object->set_tag( $this->get_tags() );
return $object;
}
/**
* Returns the ID of the Post.
*
* @return string The Posts ID.
*/
public function get_id() {
return $this->get_url();
}
/**
* Returns the URL of the Post.
*
* @return string The Posts URL.
*/
public function get_url() {
$post = $this->wp_post;
if ( 'trash' === get_post_status( $post ) ) {
$permalink = \get_post_meta( $post->ID, 'activitypub_canonical_url', true );
} else {
$permalink = \get_permalink( $post );
}
return \esc_url( $permalink );
}
/**
* Returns the User-URL of the Author of the Post.
*
* If `single_user` mode is enabled, the URL of the Blog-User is returned.
*
* @return string The User-URL.
*/
protected function get_attributed_to() {
if ( is_single_user() ) {
$user = new Blog_User();
return $user->get_url();
}
return Users::get_by_id( $this->wp_post->post_author )->get_url();
}
/**
* Generates all Media Attachments for a Post.
*
* @return array The Attachments.
*/
protected function get_attachments() {
// Once upon a time we only supported images, but we now support audio/video as well.
// We maintain the image-centric naming for backwards compatibility.
$max_media = intval( \apply_filters( 'activitypub_max_image_attachments', \get_option( 'activitypub_max_image_attachments', ACTIVITYPUB_MAX_IMAGE_ATTACHMENTS ) ) );
if ( site_supports_blocks() && \has_blocks( $this->wp_post->post_content ) ) {
return $this->get_block_attachments( $max_media );
}
return $this->get_classic_editor_images( $max_media );
}
/**
* Get media attachments from blocks. They will be formatted as ActivityPub attachments, not as WP attachments.
*
* @param int $max_media The maximum number of attachments to return.
*
* @return array The attachments.
*/
protected function get_block_attachments( $max_media ) {
// max media can't be negative or zero
if ( $max_media <= 0 ) {
return array();
}
$id = $this->wp_post->ID;
$media_ids = array();
// list post thumbnail first if this post has one
if ( \function_exists( 'has_post_thumbnail' ) && \has_post_thumbnail( $id ) ) {
$media_ids[] = \get_post_thumbnail_id( $id );
}
if ( $max_media > 0 ) {
$blocks = \parse_blocks( $this->wp_post->post_content );
$media_ids = self::get_media_ids_from_blocks( $blocks, $media_ids, $max_media );
}
$media_ids = \array_unique( $media_ids );
return \array_filter( \array_map( array( self::class, 'wp_attachment_to_activity_attachment' ), $media_ids ) );
}
/**
* Get image attachments from the classic editor.
* Note that audio/video attachments are only supported in the block editor.
*
* @param int $max_images The maximum number of images to return.
*
* @return array The attachments.
*/
protected function get_classic_editor_images( $max_images ) {
// max images can't be negative or zero
if ( $max_images <= 0 ) {
return array();
}
$id = $this->wp_post->ID;
$image_ids = array();
// list post thumbnail first if this post has one
if ( \function_exists( 'has_post_thumbnail' ) && \has_post_thumbnail( $id ) ) {
$image_ids[] = \get_post_thumbnail_id( $id );
--$max_images;
}
if ( $max_images > 0 ) {
$query = new \WP_Query(
array(
'post_parent' => $id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order ID',
'posts_per_page' => $max_images,
)
);
foreach ( $query->get_posts() as $attachment ) {
if ( ! \in_array( $attachment->ID, $image_ids, true ) ) {
$image_ids[] = $attachment->ID;
}
}
}
$image_ids = \array_unique( $image_ids );
return \array_filter( \array_map( array( self::class, 'wp_attachment_to_activity_attachment' ), $image_ids ) );
}
/**
* Recursively get media IDs from blocks.
* @param array $blocks The blocks to search for media IDs
* @param array $media_ids The media IDs to append new IDs to
* @param int $max_media The maximum number of media to return.
*
* @return array The image IDs.
*/
protected static function get_media_ids_from_blocks( $blocks, $media_ids, $max_media ) {
foreach ( $blocks as $block ) {
// recurse into inner blocks
if ( ! empty( $block['innerBlocks'] ) ) {
$media_ids = self::get_media_ids_from_blocks( $block['innerBlocks'], $media_ids, $max_media );
}
switch ( $block['blockName'] ) {
case 'core/image':
case 'core/cover':
case 'core/audio':
case 'core/video':
case 'videopress/video':
if ( ! empty( $block['attrs']['id'] ) ) {
$media_ids[] = $block['attrs']['id'];
}
break;
case 'jetpack/slideshow':
case 'jetpack/tiled-gallery':
if ( ! empty( $block['attrs']['ids'] ) ) {
$media_ids = array_merge( $media_ids, $block['attrs']['ids'] );
}
break;
case 'jetpack/image-compare':
if ( ! empty( $block['attrs']['beforeImageId'] ) ) {
$media_ids[] = $block['attrs']['beforeImageId'];
}
if ( ! empty( $block['attrs']['afterImageId'] ) ) {
$media_ids[] = $block['attrs']['afterImageId'];
}
break;
}
// stop doing unneeded work
if ( count( $media_ids ) >= $max_media ) {
break;
}
}
// still need to slice it because one gallery could knock us over the limit
return array_slice( $media_ids, 0, $max_media );
}
/**
* Converts a WordPress Attachment to an ActivityPub Attachment.
*
* @param int $id The Attachment ID.
*
* @return array The ActivityPub Attachment.
*/
public static function wp_attachment_to_activity_attachment( $id ) {
$attachment = array();
$mime_type = \get_post_mime_type( $id );
$mime_type_parts = \explode( '/', $mime_type );
// switching on image/audio/video
switch ( $mime_type_parts[0] ) {
case 'image':
$image_size = 'full';
/**
* Filter the image URL returned for each post.
*
* @param array|false $thumbnail The image URL, or false if no image is available.
* @param int $id The attachment ID.
* @param string $image_size The image size to retrieve. Set to 'full' by default.
*/
$thumbnail = apply_filters(
'activitypub_get_image',
self::get_image( $id, $image_size ),
$id,
$image_size
);
if ( $thumbnail ) {
$alt = \get_post_meta( $id, '_wp_attachment_image_alt', true );
$image = array(
'type' => 'Image',
'url' => $thumbnail[0],
'mediaType' => $mime_type,
);
if ( $alt ) {
$image['name'] = $alt;
}
$attachment = $image;
}
break;
case 'audio':
case 'video':
$attachment = array(
'type' => 'Document',
'mediaType' => $mime_type,
'url' => \wp_get_attachment_url( $id ),
'name' => \get_the_title( $id ),
);
$meta = wp_get_attachment_metadata( $id );
// height and width for videos
if ( isset( $meta['width'] ) && isset( $meta['height'] ) ) {
$attachment['width'] = $meta['width'];
$attachment['height'] = $meta['height'];
}
// @todo: add `icon` support for audio/video attachments. Maybe use post thumbnail?
break;
}
return \apply_filters( 'activitypub_attachment', $attachment, $id );
}
/**
* Return details about an image attachment.
*
* @param int $id The attachment ID.
* @param string $image_size The image size to retrieve. Set to 'full' by default.
*
* @return array|false Array of image data, or boolean false if no image is available.
*/
protected static function get_image( $id, $image_size = 'full' ) {
/**
* Hook into the image retrieval process. Before image retrieval.
*
* @param int $id The attachment ID.
* @param string $image_size The image size to retrieve. Set to 'full' by default.
*/
do_action( 'activitypub_get_image_pre', $id, $image_size );
$image = \wp_get_attachment_image_src( $id, $image_size );
/**
* Hook into the image retrieval process. After image retrieval.
*
* @param int $id The attachment ID.
* @param string $image_size The image size to retrieve. Set to 'full' by default.
*/
do_action( 'activitypub_get_image_post', $id, $image_size );
return $image;
}
/**
@ -55,7 +400,7 @@ class Post extends Base {
// Default to Article.
$object_type = 'Article';
$post_type = \get_post_type( $this->wp_post );
$post_type = \get_post_type( $this->wp_post );
switch ( $post_type ) {
case 'post':
$post_format = \get_post_format( $this->wp_post );
@ -85,7 +430,7 @@ class Post extends Base {
$object_type = 'Page';
break;
case 'attachment':
$mime_type = \get_post_mime_type();
$mime_type = \get_post_mime_type();
$media_type = \preg_replace( '/(\/[a-zA-Z]+)/i', '', $mime_type );
switch ( $media_type ) {
case 'audio':
@ -106,4 +451,154 @@ class Post extends Base {
return $object_type;
}
/**
* Returns a list of Mentions, used in the Post.
*
* @see https://docs.joinmastodon.org/spec/activitypub/#Mention
*
* @return array The list of Mentions.
*/
protected function get_cc() {
$cc = array();
$mentions = $this->get_mentions();
if ( $mentions ) {
foreach ( $mentions as $url ) {
$cc[] = $url;
}
}
return $cc;
}
/**
* Returns a list of Tags, used in the Post.
*
* This includes Hash-Tags and Mentions.
*
* @return array The list of Tags.
*/
protected function get_tags() {
$tags = array();
$post_tags = \get_the_tags( $this->wp_post->ID );
if ( $post_tags ) {
foreach ( $post_tags as $post_tag ) {
$tag = array(
'type' => 'Hashtag',
'href' => \esc_url( \get_tag_link( $post_tag->term_id ) ),
'name' => esc_hashtag( $post_tag->name ),
);
$tags[] = $tag;
}
}
$mentions = $this->get_mentions();
if ( $mentions ) {
foreach ( $mentions as $mention => $url ) {
$tag = array(
'type' => 'Mention',
'href' => \esc_url( $url ),
'name' => \esc_html( $mention ),
);
$tags[] = $tag;
}
}
return $tags;
}
/**
* Returns the content for the ActivityPub Item.
*
* The content will be generated based on the user settings.
*
* @return string The content.
*/
protected function get_content() {
global $post;
/**
* Provides an action hook so plugins can add their own hooks/filters before AP content is generated.
*
* Example: if a plugin adds a filter to `the_content` to add a button to the end of posts, it can also remove that filter here.
*
* @param WP_Post $post The post object.
*/
do_action( 'activitypub_before_get_content', $post );
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$post = $this->wp_post;
$content = $this->get_post_content_template();
// Register our shortcodes just in time.
Shortcodes::register();
// Fill in the shortcodes.
setup_postdata( $post );
$content = do_shortcode( $content );
wp_reset_postdata();
$content = \wpautop( $content );
$content = \preg_replace( '/[\n\r\t]/', '', $content );
$content = \trim( $content );
$content = \apply_filters( 'activitypub_the_content', $content, $post );
// Don't need these any more, should never appear in a post.
Shortcodes::unregister();
return $content;
}
/**
* Gets the template to use to generate the content of the activitypub item.
*
* @return string The Template.
*/
protected function get_post_content_template() {
if ( 'excerpt' === \get_option( 'activitypub_post_content_type', 'content' ) ) {
return "[ap_excerpt]\n\n[ap_permalink type=\"html\"]";
}
if ( 'title' === \get_option( 'activitypub_post_content_type', 'content' ) ) {
return "[ap_title]\n\n[ap_permalink type=\"html\"]";
}
if ( 'content' === \get_option( 'activitypub_post_content_type', 'content' ) ) {
return "[ap_content]\n\n[ap_permalink type=\"html\"]\n\n[ap_hashtags]";
}
return \get_option( 'activitypub_custom_post_content', ACTIVITYPUB_CUSTOM_POST_CONTENT );
}
/**
* Helper function to get the @-Mentions from the post content.
*
* @return array The list of @-Mentions.
*/
protected function get_mentions() {
return apply_filters( 'activitypub_extract_mentions', array(), $this->wp_post->post_content, $this->wp_post );
}
/**
* Returns the locale of the post.
*
* @return string The locale of the post.
*/
public function get_locale() {
$post_id = $this->wp_post->ID;
$lang = \strtolower( \strtok( \get_locale(), '_-' ) );
/**
* Filter the locale of the post.
*
* @param string $lang The locale of the post.
* @param int $post_id The post ID.
* @param WP_Post $post The post object.
*
* @return string The filtered locale of the post.
*/
return apply_filters( 'activitypub_post_locale', $lang, $post_id, $this->wp_post );
}
}

View file

@ -1,292 +0,0 @@
<?php
/**
* Inspired by the way elementor handles addons.
*
* @link https://github.com/elementor/elementor/
* @package Activitypub
*/
namespace Activitypub\Transformer;
use WP_Post;
use WP_Comment;
use function Activitypub\camel_to_snake_case;
use function Activitypub\snake_to_camel_case;
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
/**
* ActivityPub transformers manager.
*
* ActivityPub transformers manager handler class is responsible for registering and
* initializing all the supported WP-Pobject to ActivityPub transformers.
*
* @since version_number_transformer_management_placeholder
*/
class Transformers_Manager {
const DEFAULT_TRANSFORMER_MAPPING = array(
'post' => ACTIVITYPUB_DEFAULT_TRANSFORMER,
'page' => ACTIVITYPUB_DEFAULT_TRANSFORMER,
);
/**
* Transformers.
*
* Holds the list of all the ActivityPub transformers. Default is `null`.
*
* @since version_number_transformer_management_placeholder
* @access private
*
* @var \ActivityPub\Transformer\Base[]
*/
private $transformers = null;
/**
* Transformer_Manager instance.
*
* Holds the transformer instance.
*
* @since version_number_transformer_management_placeholder
* @access protected
*
* @var Transformer_Manager
*/
protected static $_instances = [];
/**
* Instance.
*
* Ensures only one instance of the transformer manager class is loaded or can be loaded.
*
* @since version_number_transformer_management_placeholder
* @access public
* @static
*
* @return Transformer_Manager An instance of the class.
*/
public static function instance() {
$class_name = static::class_name();
if ( empty( static::$_instances[ $class_name ] ) ) {
static::$_instances[ $class_name ] = new static();
}
return static::$_instances[ $class_name ];
}
/**
* Class name.
*
* Retrieve the name of the class.
*
* @since version_number_transformer_management_placeholder
* @access public
* @static
*/
public static function class_name() {
return get_called_class();
}
/**
* Transformers manager constructor.
*
* Initializing ActivityPub transformers manager.
*
* @since version_number_transformer_management_placeholder
* @access public
*/
public function __construct() {
$this->require_files();
}
/**
* Require files.
*
* Require ActivityPub transformer base class.
*
* @since version_number_transformer_management_placeholder
* @access private
*/
private function require_files() {
require ACTIVITYPUB_PLUGIN_DIR . 'includes/transformer/class-base.php';
}
/**
* Checks if a transformer is registered.
*
* @since version_number_transformer_management_placeholder
*
* @param string $name Transformer name including namespace.
* @return bool True if the block type is registered, false otherwise.
*/
public function is_registered( $name ) {
return isset( $this->transformers[ $name ] );
}
/**
* Register a transformer.
*
* @since version_number_transformer_management_placeholder
* @access public
*
* @param \ActivityPub\Transformer\Base $transformer_instance ActivityPub Transformer.
*
* @return bool True if the ActivityPub transformer was registered.
*/
public function register( \ActivityPub\Transformer\Base $transformer_instance ) {
if ( ! $transformer_instance instanceof \ActivityPub\Transformer\Base ) {
_doing_it_wrong(
__METHOD__,
\esc_html__( 'ActivityPub transformer instance must be a of \ActivityPub\Transformer_Base class.' ),
'version_number_transformer_management_placeholder'
);
return false;
}
$transformer_name = $transformer_instance->get_name();
if ( preg_match( '/[A-Z]+/', $transformer_name ) ) {
_doing_it_wrong(
__METHOD__,
\esc_html__( 'ActivityPub transformer names must not contain uppercase characters.' ),
'version_number_transformer_management_placeholder'
);
return false;
}
$name_matcher = '/^[a-z0-9-]+\/[a-z0-9-]+$/';
if ( ! preg_match( $name_matcher, $transformer_name ) ) {
_doing_it_wrong(
__METHOD__,
\esc_html__( 'ActivityPub transformer names must contain a namespace prefix. Example: my-plugin/my-custom-transformer' ),
'version_number_transformer_management_placeholder'
);
return false;
}
if ( $this->is_registered( $transformer_name ) ) {
_doing_it_wrong(
__METHOD__,
/* translators: %s: Block name. */
sprintf( 'ActivityPub transformer with name "%s" is already registered.', esc_html( $transformer_name ) ),
'version_number_transformer_management_placeholder'
);
return false;
}
/**
* Should the ActivityPub transformer be registered.
*
* @since version_number_transformer_management_placeholder
*
* @param bool $should_register Should the ActivityPub transformer be registered. Default is `true`.
* @param \ActivityPub\Transformer\Base $transformer_instance Widget instance.
*/
// TODO: does not implementing this slow down the website? -> compare with gutenberg block registration.
// $should_register = apply_filters( 'activitypub/transformers/is_transformer_enabled', true, $transformer_instance );
// if ( ! $should_register ) {
// return false;
// }
$this->transformers[ $transformer_name ] = $transformer_instance;
return true;
}
/**
* Init transformers.
*
* Initialize ActivityPub transformer manager.
* Include the builtin transformers by default and add third party ones.
*
* @since version_number_transformer_management_placeholder
* @access private
*/
private function init_transformers() {
$builtin_transformers = [
'post',
];
$this->transformers = [];
foreach ( $builtin_transformers as $transformer_name ) {
include ACTIVITYPUB_PLUGIN_DIR . 'includes/transformer/class-' . $transformer_name . '.php';
$class_name = ucfirst( $transformer_name );
$class_name = '\Activitypub\Transformer\\' . $class_name;
$this->register( new $class_name() );
}
/**
* Let other transformers register.
*
* Fires after the built-in Activitypub transformers are registered.
*
* @since version_number_transformer_management_placeholder
*
* @param Transformers_Manager $this The widgets manager.
*/
do_action( 'activitypub_transformers_register', $this );
}
/**
* Get available ActivityPub transformers.
*
* Retrieve the registered transformers list. If given a transformer name
* it returns the given transformer if it is registered.
*
* @since version_number_transformer_management_placeholder
* @access public
*
* @param string $transformer_name Optional. Transformer name. Default is null.
*
* @return Base|Base[]|null Registered transformers.
*/
public function get_transformers( $transformer_name = null ) {
if ( is_null( $this->transformers ) ) {
$this->init_transformers();
}
if ( null !== $transformer_name ) {
return isset( $this->transformers[ $transformer_name ] ) ? $this->transformers[ $transformer_name ] : null;
}
return $this->transformers;
}
/**
* Get the mapped ActivityPub transformer.
*
* Returns a new instance of the needed WordPress to ActivityPub transformer.
*
* @since version_number_transformer_management_placeholder
* @access public
*
* @param WP_Post|WP_Comment $object The WordPress Post/Comment.
*
* @return \ActivityPub\Transformer\Base|null Registered transformers.
*/
public function get_transformer( $object ) {
switch ( get_class( $object ) ) {
case 'WP_Post':
$post_type = get_post_type( $object );
$transformer_mapping = \get_option( 'activitypub_transformer_mapping', self::DEFAULT_TRANSFORMER_MAPPING );
$transformer_name = $transformer_mapping[ $post_type ];
$transformer_class = $this->get_transformers( $transformer_name );
$transformer_instance = new $transformer_class();
$transformer_instance->set_wp_post( $object );
return $transformer_instance;
case 'WP_Comment':
return new Comment( $object );
default:
return apply_filters( 'activitypub_transformer', null, $object, get_class( $object ) );
}
}
}

View file

@ -30,10 +30,6 @@ class Webfinger {
public static function add_user_discovery( $array, $resource, $user ) {
$user = User_Collection::get_by_id( $user->ID );
if ( ! $user || is_wp_error( $user ) ) {
return $array;
}
$array['links'][] = array(
'rel' => 'self',
'type' => 'application/activity+json',

View file

@ -3,7 +3,7 @@ Contributors: automattic, pfefferle, mediaformat, mattwiebe, akirk, jeherve, nur
Tags: OStatus, fediverse, activitypub, activitystream
Requires at least: 4.7
Tested up to: 6.4
Stable tag: 1.2.0
Stable tag: 1.1.0
Requires PHP: 5.6
License: MIT
License URI: http://opensource.org/licenses/MIT
@ -105,15 +105,6 @@ Where 'blog' is the path to the subdirectory at which your blog resides.
Project maintained on GitHub at [automattic/wordpress-activitypub](https://github.com/automattic/wordpress-activitypub).
= 1.2.0 =
* Add: Search and order followerer lists
* Add: Have a filter to defer signature verification
* Improved: "Follow Me" styles for dark themes
* Improved: Allow `p` and `br` tags only for AP comments
* Fixed: Deduplicate attachments earlier to prevent incorrect max_media
= 1.1.0 =
* Improved: audio and video attachments are now supported!

View file

@ -21,8 +21,8 @@ $followers_template = _n( 'Your blog profile currently has %s follower.', 'Your
<input type="hidden" name="tab" value="followers" />
<?php
$table->prepare_items();
$table->search_box( 'Search', 'search' );
$table->display();
?>
<?php wp_nonce_field( 'activitypub-followers-list', '_apnonce' ); ?>
</form>
</div>

View file

@ -2,9 +2,8 @@
// phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
$post = \get_post();
$transformer = \Activitypub\Transformer\Transformers_Manager::instance()->get_transformer( $post );
$json = \array_merge( array( '@context' => \Activitypub\get_context() ), $transformer->to_object()->to_array() );
$object = new \Activitypub\Transformer\Post( $post );
$json = \array_merge( array( '@context' => \Activitypub\get_context() ), $object->to_object()->to_array() );
// filter output
$json = \apply_filters( 'activitypub_json_post_array', $json );

View file

@ -201,6 +201,26 @@
</p>
</td>
</tr>
<tr>
<th scope="row"><?php \esc_html_e( 'Supported post types', 'activitypub' ); ?></th>
<td>
<fieldset>
<?php \esc_html_e( 'Enable ActivityPub support for the following post types:', 'activitypub' ); ?>
<?php $post_types = \get_post_types( array( 'public' => true ), 'objects' ); ?>
<?php $support_post_types = \get_option( 'activitypub_support_post_types', array( 'post', 'page' ) ) ? \get_option( 'activitypub_support_post_types', array( 'post', 'page' ) ) : array(); ?>
<ul>
<?php // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited ?>
<?php foreach ( $post_types as $post_type ) { ?>
<li>
<input type="checkbox" id="activitypub_support_post_type_<?php echo \esc_attr( $post_type->name ); ?>" name="activitypub_support_post_types[]" value="<?php echo \esc_attr( $post_type->name ); ?>" <?php echo \checked( \in_array( $post_type->name, $support_post_types, true ) ); ?> />
<label for="activitypub_support_post_type_<?php echo \esc_attr( $post_type->name ); ?>"><?php echo \esc_html( $post_type->label ); ?></label>
</li>
<?php } ?>
</ul>
</fieldset>
</td>
</tr>
<tr>
<th scope="row">
<?php \esc_html_e( 'Hashtags (beta)', 'activitypub' ); ?>
@ -217,93 +237,6 @@
<?php \do_settings_fields( 'activitypub', 'activity' ); ?>
</div>
<!-- OUR FORK HERE -->
<div class="box">
<h3><?php \esc_html_e( 'Enable ActivityPub support for post type', 'activitypub' ); ?></h3>
<table class="form-table">
<tbody>
<tr>
<th scope="row">
<?php \esc_html_e( 'Mapping', 'activitypub' ); ?>
</th>
<td>
<?php \esc_html_e( 'Enable ActivityPub support for a certain post type by selecting one of the available ActivityPub transformers.', 'activitypub' ); ?>
<?php $all_public_post_types = \get_post_types( array( 'public' => true ), 'objects' );
$transformer_mapping = \get_option( 'activitypub_transformer_mapping', array( 'default' => 'note' ) );
$all_public_post_type_names = array_map(function ($object) {
return $object->name;
}, $all_public_post_types);
$transformer_manager = \Activitypub\Transformer\Transformers_Manager::instance();
$transformers = $transformer_manager->get_transformers();
?>
<script>
// TODO Probably we should use checkboxes and not select and make this less buggy and insert the js at the right place.
document.addEventListener('DOMContentLoaded', function () {
var radioGroups = {};
var radioButtons = document.querySelectorAll('input[type="radio"]');
radioButtons.forEach(function (radioButton) {
radioButton.addEventListener('click', function () {
var name = this.name;
if (!radioGroups[name]) {
radioGroups[name] = this;
} else {
radioGroups[name].checked = false;
radioGroups[name] = this;
}
});
});
});
</script>
<table>
<thead>
<tr>
<th></th>
<?php
// Generate column headers based on transformer objects
foreach ($transformers as $transformer) {
echo '<th>' . htmlspecialchars($transformer->get_label()) . '</th>';
}
?>
</tr>
</thead>
<tbody>
<?php
// Generate rows based on post types and transformers
foreach ($all_public_post_types as $post_type) {
echo '<tr>';
echo '<td><strong>' . htmlspecialchars($post_type->label) . '</strong></td>';
// Generate radio inputs for each transformer, considering support for the post type
foreach ($transformers as $transformer) {
$disabled_attribute = $transformer->supports_post_type( $post_type->name ) ? '' : ' disabled';
$is_selected = ( is_array( $transformer_mapping ) && isset( $transformer_mapping[ $post_type->name ] ) && $transformer_mapping[ $post_type->name ] === $transformer->get_name() ) ? ' checked ' : '';
echo '<td><input type="radio" name="activitypub_transformer_mapping[' . $post_type->name . ']" value="' . $transformer->get_name() . '"' . $is_selected . $disabled_attribute . '></td>';
}
echo '</tr>';
}
?>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</div>
<!-- OUR FORK ENDS HERE -->
<div class="box">
<h3><?php \esc_html_e( 'Server', 'activitypub' ); ?></h3>
<table class="form-table">

View file

@ -14,8 +14,8 @@ $followers_template = _n( 'Your author profile currently has %s follower.', 'You
<input type="hidden" name="page" value="activitypub-followers-list" />
<?php
$table->prepare_items();
$table->search_box( 'Search', 'search' );
$table->display();
?>
<?php wp_nonce_field( 'activitypub-followers-list', '_apnonce' ); ?>
</form>
</div>

View file

@ -1,4 +1,6 @@
<?php
use DMS\PHPUnitExtensions\ArraySubset\Assert;
class Test_Activitypub_Activity extends WP_UnitTestCase {
public function test_activity_mentions() {
$post = \wp_insert_post(
@ -17,8 +19,7 @@ class Test_Activitypub_Activity extends WP_UnitTestCase {
10
);
$wp_post = get_post( $post );
$activitypub_post = \Activitypub\Transformer\Transformers_Manager::instance()->get_transformer( $post )->to_object();
$activitypub_post = \Activitypub\Transformer\Post::transform( get_post( $post ) )->to_object();
$activitypub_activity = new \Activitypub\Activity\Activity();
$activitypub_activity->set_type( 'Create' );
@ -43,4 +44,21 @@ class Test_Activitypub_Activity extends WP_UnitTestCase {
$this->assertEquals( 'Hello world!', $object->get_content() );
$this->assertEquals( $test_array, $object->to_array() );
}
public function test_activity_object() {
$test_array = array(
'id' => 'https://example.com/post/123',
'type' => 'Create',
'object' => array(
'id' => 'https://example.com/post/123/activity',
'type' => 'Note',
'content' => 'Hello world!',
),
);
$activity = \Activitypub\Activity\Activity::init_from_array( $test_array );
$this->assertEquals( 'Hello world!', $activity->get_object()->get_content() );
Assert::assertArraySubset( $test_array, $activity->to_array() );
}
}

View file

@ -0,0 +1,70 @@
<?php
class Test_Activitypub_Create_Handler extends WP_UnitTestCase {
public $user_id;
public $user_url;
public $post_id;
public $post_permalink;
public function set_up() {
$this->user_id = 1;
$authordata = \get_userdata( $this->user_id );
$this->user_url = $authordata->user_url;
$this->post_id = \wp_insert_post(
array(
'post_author' => $this->user_id,
'post_content' => 'test',
)
);
$this->post_permalink = \get_permalink( $this->post_id );
\add_filter( 'pre_get_remote_metadata_by_actor', array( '\Test_Activitypub_Create_Handler', 'get_remote_metadata_by_actor' ), 0, 2 );
}
public static function get_remote_metadata_by_actor( $value, $actor ) {
return array(
'name' => 'Example User',
'icon' => array(
'url' => 'https://example.com/icon',
),
'url' => $actor,
'id' => 'http://example.org/users/example',
);
}
public function create_test_object( $id = 'https://example.com/123' ) {
return array(
'actor' => $this->user_url,
'id' => 'https://example.com/id/' . microtime( true ),
'to' => [ $this->user_url ],
'cc' => [ 'https://www.w3.org/ns/activitystreams#Public' ],
'object' => array(
'id' => $id,
'url' => 'https://example.com/example',
'inReplyTo' => $this->post_permalink,
'content' => 'example',
),
);
}
public function test_handle_create_object_unset_rejected() {
$object = $this->create_test_object();
unset( $object['object'] );
$converted = Activitypub\Handler\Create::handle_create( $object, $this->user_id );
$this->assertEquals( $converted->get_error_code(), 'activitypub_no_valid_object' );
}
public function test_handle_create_non_public_rejected() {
$object = $this->create_test_object();
$object['cc'] = [];
$converted = Activitypub\Handler\Create::handle_create( $object, $this->user_id );
$this->assertEquals( $converted->get_error_code(), 'activitypub_activity_not_public' );
}
public function test_handle_create_no_id_rejected() {
$object = $this->create_test_object();
unset( $object['object']['id'] );
$converted = Activitypub\Handler\Create::handle_create( $object, $this->user_id );
$this->assertEquals( $converted->get_error_code(), 'activitypub_no_valid_object' );
}
}

View file

@ -1,5 +1,5 @@
<?php
class Test_Db_Activitypub_Followers extends WP_UnitTestCase {
class Test_Activitypub_Followers extends WP_UnitTestCase {
public static $users = array(
'username@example.org' => array(
'id' => 'https://example.org/users/username',

View file

@ -0,0 +1,112 @@
<?php
class Test_Activitypub_Interactions extends WP_UnitTestCase {
public $user_id;
public $user_url;
public $post_id;
public $post_permalink;
public function set_up() {
$this->user_id = 1;
$authordata = \get_userdata( $this->user_id );
$this->user_url = $authordata->user_url;
$this->post_id = \wp_insert_post(
array(
'post_author' => $this->user_id,
'post_content' => 'test',
)
);
$this->post_permalink = \get_permalink( $this->post_id );
\add_filter( 'pre_get_remote_metadata_by_actor', array( '\Test_Activitypub_Interactions', 'get_remote_metadata_by_actor' ), 0, 2 );
}
public static function get_remote_metadata_by_actor( $value, $actor ) {
return array(
'name' => 'Example User',
'icon' => array(
'url' => 'https://example.com/icon',
),
'url' => $actor,
'id' => 'http://example.org/users/example',
);
}
public function create_test_object( $id = 'https://example.com/123' ) {
return array(
'actor' => $this->user_url,
'id' => 'https://example.com/id/' . microtime( true ),
'to' => [ $this->user_url ],
'cc' => [ 'https://www.w3.org/ns/activitystreams#Public' ],
'object' => array(
'id' => $id,
'url' => 'https://example.com/example',
'inReplyTo' => $this->post_permalink,
'content' => 'example',
),
);
}
public function test_handle_create_basic() {
$comment_id = Activitypub\Collection\Interactions::add_comment( $this->create_test_object() );
$comment = get_comment( $comment_id, ARRAY_A );
$this->assertIsArray( $comment );
$this->assertEquals( $this->post_id, $comment['comment_post_ID'] );
$this->assertEquals( 'Example User', $comment['comment_author'] );
$this->assertEquals( $this->user_url, $comment['comment_author_url'] );
$this->assertEquals( 'example', $comment['comment_content'] );
$this->assertEquals( 'comment', $comment['comment_type'] );
$this->assertEquals( '', $comment['comment_author_email'] );
$this->assertEquals( 0, $comment['comment_parent'] );
$this->assertEquals( 'https://example.com/123', get_comment_meta( $comment_id, 'source_id', true ) );
$this->assertEquals( 'https://example.com/example', get_comment_meta( $comment_id, 'source_url', true ) );
$this->assertEquals( 'https://example.com/icon', get_comment_meta( $comment_id, 'avatar_url', true ) );
$this->assertEquals( 'activitypub', get_comment_meta( $comment_id, 'protocol', true ) );
}
public function test_convert_object_to_comment_not_reply_rejected() {
$object = $this->create_test_object();
unset( $object['object']['inReplyTo'] );
$converted = Activitypub\Collection\Interactions::add_comment( $object );
$this->assertEquals( $converted->get_error_code(), 'activitypub_no_reply' );
}
public function test_convert_object_to_comment_already_exists_rejected() {
$object = $this->create_test_object( 'https://example.com/test_convert_object_to_comment_already_exists_rejected' );
Activitypub\Collection\Interactions::add_comment( $object );
$converted = Activitypub\Collection\Interactions::add_comment( $object );
$this->assertEquals( $converted->get_error_code(), 'comment_duplicate' );
}
public function test_convert_object_to_comment_reply_to_comment() {
$id = 'https://example.com/test_convert_object_to_comment_reply_to_comment';
$object = $this->create_test_object( $id );
Activitypub\Collection\Interactions::add_comment( $object );
$comment = \Activitypub\object_id_to_comment( $id );
$object['object']['inReplyTo'] = $id;
$object['object']['id'] = 'https://example.com/234';
$id = Activitypub\Collection\Interactions::add_comment( $object );
$converted = get_comment( $id, ARRAY_A );
$this->assertIsArray( $converted );
$this->assertEquals( $this->post_id, $converted['comment_post_ID'] );
$this->assertEquals( $comment->comment_ID, $converted['comment_parent'] );
}
public function test_convert_object_to_comment_reply_to_non_existent_comment_rejected() {
$object = $this->create_test_object();
$object['object']['inReplyTo'] = 'https://example.com/not_found';
$converted = Activitypub\Collection\Interactions::add_comment( $object );
$this->assertEquals( $converted->get_error_code(), 'activitypub_no_reply' );
}
public function test_handle_create_basic2() {
$id = 'https://example.com/test_handle_create_basic';
$object = $this->create_test_object( $id );
Activitypub\Collection\Interactions::add_comment( $object );
$comment = \Activitypub\object_id_to_comment( $id );
$this->assertInstanceOf( WP_Comment::class, $comment );
}
}

View file

@ -10,13 +10,13 @@ class Test_Activitypub_Post extends WP_UnitTestCase {
$permalink = \get_permalink( $post );
$activitypub_post = \Activitypub\Transformer\Transformers_Manager::instance()->get_transformer( get_post( $post ) )->to_object();
$activitypub_post = \Activitypub\Transformer\Post::transform( get_post( $post ) )->to_object();
$this->assertEquals( $permalink, $activitypub_post->get_id() );
\wp_trash_post( $post );
$activitypub_post = \Activitypub\Transformer\Transformers_Manager::instance()->get_transformer( get_post( $post ) )->to_object();
$activitypub_post = \Activitypub\Transformer\Post::transform( get_post( $post ) )->to_object();
$this->assertEquals( $permalink, $activitypub_post->get_id() );

View file

@ -5,7 +5,7 @@ class Test_Activitypub_Rest_Inbox extends WP_UnitTestCase {
*/
public function test_is_activity_public( $data, $check ) {
$this->assertEquals( $check, Activitypub\Rest\Inbox::is_activity_public( $data ) );
$this->assertEquals( $check, Activitypub\is_activity_public( $data ) );
}
public function the_data_provider() {

View file

@ -10,7 +10,7 @@ class Test_Activitypub_Signature_Verification extends WP_UnitTestCase {
)
);
$remote_actor = \get_author_posts_url( 2 );
$activitypub_post = \Activitypub\Transformer\Transformers_Manager::instance()->get_transformer( get_post( $post ) )->to_object();
$activitypub_post = \Activitypub\Transformer\Post::transform( get_post( $post ) )->to_object();
$activitypub_activity = new Activitypub\Activity\Activity( 'Create' );
$activitypub_activity->set_type( 'Create' );
$activitypub_activity->set_object( $activitypub_post );
@ -82,7 +82,7 @@ class Test_Activitypub_Signature_Verification extends WP_UnitTestCase {
);
$remote_actor = \get_author_posts_url( 2 );
$remote_actor_inbox = Activitypub\get_rest_url_by_path( '/inbox' );
$activitypub_post = \Activitypub\Transformer\Transformers_Manager::instance()->get_transformer( get_post( $post ) )->to_object();
$activitypub_post = \Activitypub\Transformer\Post::transform( \get_post( $post ) )->to_object();
$activitypub_activity = new Activitypub\Activity\Activity();
$activitypub_activity->set_type( 'Create' );
$activitypub_activity->set_object( $activitypub_post );

View file

@ -1,9 +1,80 @@
<?php
class Test_Functions extends ActivityPub_TestCase_Cache_HTTP {
public $user_id;
public $post_id;
public function test_get_remote_metadata_by_actor() {
$metadata = \ActivityPub\get_remote_metadata_by_actor( 'pfefferle@notiz.blog' );
$this->assertEquals( 'https://notiz.blog/author/matthias-pfefferle/', $metadata['url'] );
$this->assertEquals( 'pfefferle', $metadata['preferredUsername'] );
$this->assertEquals( 'Matthias Pfefferle', $metadata['name'] );
}
public function set_up() {
$this->post_id = \wp_insert_post(
array(
'post_author' => $this->user_id,
'post_content' => 'test',
)
);
}
public function test_object_id_to_comment_basic() {
$single_comment_source_id = 'https://example.com/single';
$content = 'example';
$comment_id = \wp_new_comment(
array(
'comment_post_ID' => $this->post_id,
'comment_author' => 'Example User',
'comment_author_url' => 'https://example.com/user',
'comment_content' => $content,
'comment_type' => '',
'comment_author_email' => '',
'comment_parent' => 0,
'comment_meta' => array(
'source_id' => $single_comment_source_id,
'source_url' => 'https://example.com/123',
'avatar_url' => 'https://example.com/icon',
'protocol' => 'activitypub',
),
),
true
);
$query_result = \Activitypub\object_id_to_comment( $single_comment_source_id );
$this->assertInstanceOf( WP_Comment::class, $query_result );
$this->assertEquals( $comment_id, $query_result->comment_ID );
$this->assertEquals( $content, $query_result->comment_content );
}
public function test_object_id_to_comment_none() {
$single_comment_source_id = 'https://example.com/none';
$query_result = \Activitypub\object_id_to_comment( $single_comment_source_id );
$this->assertFalse( $query_result );
}
public function test_object_id_to_comment_duplicate() {
$duplicate_comment_source_id = 'https://example.com/duplicate';
for ( $i = 0; $i < 2; ++$i ) {
\wp_new_comment(
array(
'comment_post_ID' => $this->post_id,
'comment_author' => 'Example User',
'comment_author_url' => 'https://example.com/user',
'comment_content' => 'example',
'comment_type' => '',
'comment_author_email' => '',
'comment_parent' => 0,
'comment_meta' => array(
'source_id' => $duplicate_comment_source_id,
'source_url' => 'https://example.com/123',
'avatar_url' => 'https://example.com/icon',
'protocol' => 'activitypub',
),
),
true
);
}
$query_result = \Activitypub\object_id_to_comment( $duplicate_comment_source_id );
$this->assertFalse( $query_result );
}
}