| 1 |
<?php |
| 2 |
/** |
| 3 |
* ActivityPub Post REST Endpoints |
| 4 |
* |
| 5 |
* @package Activitypub |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Activitypub\Rest; |
| 9 |
|
| 10 |
use WP_REST_Server; |
| 11 |
use WP_REST_Response; |
| 12 |
use WP_Error; |
| 13 |
use Activitypub\Comment; |
| 14 |
|
| 15 |
/** |
| 16 |
* Class Post |
| 17 |
* |
| 18 |
* @package Activitypub\Rest |
| 19 |
*/ |
| 20 |
class Post { |
| 21 |
|
| 22 |
/** |
| 23 |
* Initialize the class and register routes. |
| 24 |
*/ |
| 25 |
public static function init() { |
| 26 |
self::register_routes(); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Register routes. |
| 31 |
*/ |
| 32 |
public static function register_routes() { |
| 33 |
register_rest_route( |
| 34 |
ACTIVITYPUB_REST_NAMESPACE, |
| 35 |
'/posts/(?P<id>\d+)/reactions', |
| 36 |
array( |
| 37 |
'methods' => WP_REST_Server::READABLE, |
| 38 |
'callback' => array( static::class, 'get_reactions' ), |
| 39 |
'permission_callback' => '__return_true', |
| 40 |
'args' => array( |
| 41 |
'id' => array( |
| 42 |
'required' => true, |
| 43 |
'type' => 'integer', |
| 44 |
), |
| 45 |
), |
| 46 |
) |
| 47 |
); |
| 48 |
} |
| 49 |
|
| 50 |
/** |
| 51 |
* Get reactions for a post. |
| 52 |
* |
| 53 |
* @param \WP_REST_Request $request The request. |
| 54 |
* |
| 55 |
* @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. |
| 56 |
*/ |
| 57 |
public static function get_reactions( $request ) { |
| 58 |
$post_id = $request->get_param( 'id' ); |
| 59 |
$post = get_post( $post_id ); |
| 60 |
|
| 61 |
if ( ! $post ) { |
| 62 |
return new WP_Error( 'post_not_found', 'Post not found', array( 'status' => 404 ) ); |
| 63 |
} |
| 64 |
|
| 65 |
$reactions = array(); |
| 66 |
|
| 67 |
foreach ( Comment::get_comment_types() as $type_object ) { |
| 68 |
$comments = get_comments( |
| 69 |
array( |
| 70 |
'post_id' => $post_id, |
| 71 |
'type' => $type_object['type'], |
| 72 |
'status' => 'approve', |
| 73 |
) |
| 74 |
); |
| 75 |
|
| 76 |
if ( empty( $comments ) ) { |
| 77 |
continue; |
| 78 |
} |
| 79 |
|
| 80 |
$count = count( $comments ); |
| 81 |
// phpcs:disable WordPress.WP.I18n |
| 82 |
$label = sprintf( |
| 83 |
_n( |
| 84 |
$type_object['count_single'], |
| 85 |
$type_object['count_plural'], |
| 86 |
$count, |
| 87 |
'activitypub' |
| 88 |
), |
| 89 |
number_format_i18n( $count ) |
| 90 |
); |
| 91 |
// phpcs:enable WordPress.WP.I18n |
| 92 |
|
| 93 |
$reactions[ $type_object['collection'] ] = array( |
| 94 |
'label' => $label, |
| 95 |
'items' => array_map( |
| 96 |
function ( $comment ) { |
| 97 |
return array( |
| 98 |
'name' => $comment->comment_author, |
| 99 |
'url' => $comment->comment_author_url, |
| 100 |
'avatar' => get_comment_meta( $comment->comment_ID, 'avatar_url', true ), |
| 101 |
); |
| 102 |
}, |
| 103 |
$comments |
| 104 |
), |
| 105 |
); |
| 106 |
} |
| 107 |
|
| 108 |
return new WP_REST_Response( $reactions ); |
| 109 |
} |
| 110 |
} |
| 111 |
|