Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.78% covered (success)
90.78%
128 / 141
71.43% covered (warning)
71.43%
5 / 7
CRAP
0.00% covered (danger)
0.00%
0 / 1
Related_Posts_Abilities
92.09% covered (success)
92.09%
128 / 139
71.43% covered (warning)
71.43%
5 / 7
34.57
0.00% covered (danger)
0.00%
0 / 1
 get_category_slug
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_category_definition
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 get_abilities
100.00% covered (success)
100.00%
77 / 77
100.00% covered (success)
100.00%
1 / 1
1
 can_view_related_posts
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_related_posts
76.74% covered (warning)
76.74%
33 / 43
0.00% covered (danger)
0.00%
0 / 1
23.54
 related_posts_instance
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 summarize_related_post
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
9
1<?php
2/**
3 * Jetpack Related Posts Abilities Registration
4 *
5 * Registers Jetpack Related Posts abilities with the WordPress Abilities API.
6 *
7 * @package automattic/jetpack
8 */
9
10namespace Automattic\Jetpack\Plugin\Abilities;
11
12use Automattic\Jetpack\WP_Abilities\Registrar;
13use Jetpack_RelatedPosts;
14use WP_Error;
15
16if ( ! defined( 'ABSPATH' ) ) {
17    exit( 0 );
18}
19
20/**
21 * Registers Jetpack Related Posts abilities with the WordPress Abilities API.
22 *
23 * Exposes related-post lookups through the standard `wp-abilities/v1` REST
24 * surface. Display-settings management is intentionally not exposed: classic
25 * themes consume the `relatedposts` option only when an off-by-default filter
26 * is enabled, and block themes ignore it altogether (rendering is controlled
27 * per-instance by the Jetpack Related Posts block in templates) — so an agent
28 * editing those values would be writing data nothing reads.
29 */
30class Related_Posts_Abilities extends Registrar {
31
32    // Mirrors the cap the upstream Related Posts ES query enforces; raising it
33    // here would be silently truncated downstream.
34    private const MAX_SIZE = 20;
35
36    private const DEFAULT_SIZE = 3;
37
38    /**
39     * Returns the category slug this registrar owns.
40     */
41    public static function get_category_slug(): string {
42        return 'jetpack-related-posts';
43    }
44
45    /**
46     * Returns the category definition passed to wp_register_ability_category().
47     */
48    public static function get_category_definition(): array {
49        return array(
50            // "Jetpack" is a product name and should not be translated.
51            'label'       => 'Jetpack Related Posts',
52            'description' => __( 'Abilities for reading related posts.', 'jetpack' ),
53        );
54    }
55
56    /**
57     * Returns the abilities this registrar owns as a [ slug => spec ] map.
58     */
59    public static function get_abilities(): array {
60        $related_post_schema = array(
61            'type'       => 'object',
62            'properties' => array(
63                'id'        => array( 'type' => 'integer' ),
64                'url'       => array( 'type' => 'string' ),
65                'title'     => array( 'type' => 'string' ),
66                'excerpt'   => array( 'type' => 'string' ),
67                'date'      => array( 'type' => 'string' ),
68                'post_type' => array( 'type' => 'string' ),
69                'format'    => array( 'type' => array( 'string', 'null' ) ),
70            ),
71        );
72
73        return array(
74            'jetpack-related-posts/get-related-posts' => array(
75                'label'               => __( 'Get related posts', 'jetpack' ),
76                'description'         => __( 'Return related posts for a single post as an array of { id, url, title, excerpt, date, post_type, format }. The caller must be able to edit the source post (edit_post capability); unauthorized requests return jetpack_related_posts_forbidden. Backed by Elasticsearch via the Jetpack connection: when Related Posts is disabled, the post is unknown, or the ES backend is unreachable, the array is empty (not an error). Use per_page to control the result count (1..20, default 20); the underlying Elasticsearch query is hard-capped at 20, so values above 20 are rejected by the input schema and pagination beyond the first 20 results is not supported. The legacy "size" alias is accepted for backward compatibility and defaults to 3 when no per_page is supplied. Read-only and idempotent. Use jetpack/get-modules to confirm the related-posts module is active, jetpack/set-module-status to activate it.', 'jetpack' ),
77                'input_schema'        => array(
78                    'type'                 => 'object',
79                    'required'             => array( 'post_id' ),
80                    'properties'           => array(
81                        'post_id'          => array(
82                            'type'        => 'integer',
83                            'description' => __( 'WordPress post ID to find related posts for. Must reference an existing post.', 'jetpack' ),
84                            'minimum'     => 1,
85                        ),
86                        'per_page'         => array(
87                            'type'        => 'integer',
88                            'description' => __( 'Maximum number of related posts to return per call. Must be between 1 and 20 — the Elasticsearch backend hard-caps results at 20, so larger values are not supported and pagination past the first 20 results is unavailable. Defaults to 20.', 'jetpack' ),
89                            'minimum'     => 1,
90                            'maximum'     => self::MAX_SIZE,
91                            'default'     => self::MAX_SIZE,
92                        ),
93                        'size'             => array(
94                            'type'        => 'integer',
95                            'description' => __( 'Deprecated alias for per_page. Defaults to 3 when per_page is omitted. Capped at 20.', 'jetpack' ),
96                            'minimum'     => 1,
97                            'maximum'     => self::MAX_SIZE,
98                            'default'     => self::DEFAULT_SIZE,
99                        ),
100                        'post_type'        => array(
101                            'type'        => 'string',
102                            'description' => __( 'Restrict matches to a single post type slug (e.g. "post", "page"). Defaults to the source post\'s type.', 'jetpack' ),
103                            'minLength'   => 1,
104                        ),
105                        'exclude_post_ids' => array(
106                            'type'        => 'array',
107                            'description' => __( 'Post IDs to exclude from the result.', 'jetpack' ),
108                            'items'       => array(
109                                'type'    => 'integer',
110                                'minimum' => 1,
111                            ),
112                            'default'     => array(),
113                        ),
114                    ),
115                    'additionalProperties' => false,
116                ),
117                'output_schema'       => array(
118                    'type'  => 'array',
119                    'items' => $related_post_schema,
120                ),
121                'execute_callback'    => array( __CLASS__, 'get_related_posts' ),
122                'permission_callback' => array( __CLASS__, 'can_view_related_posts' ),
123                'meta'                => array(
124                    'annotations'  => array(
125                        'readonly'    => true,
126                        'destructive' => false,
127                        'idempotent'  => true,
128                    ),
129                    'public'       => true,
130                    'show_in_rest' => true,
131                    'mcp'          => array(
132                        'public' => true,
133                        'type'   => 'tool', // default is already "tool", but can be explicit.
134                    ),
135                ),
136            ),
137        );
138    }
139
140    /**
141     * Permission gate for the ability menu.
142     *
143     * Returns true if the caller can edit any post — keeps the ability listed
144     * for agents that have at least one editable post. The actual per-post
145     * authorization runs inside `get_related_posts()` once the source post_id
146     * is known, mirroring the existing /wpcom/v2/related-posts/{id} endpoint.
147     */
148    public static function can_view_related_posts(): bool {
149        return current_user_can( 'edit_posts' );
150    }
151
152    /**
153     * Execute: return related posts for a given post.
154     *
155     * @param array|null $input Input matching the ability's input_schema.
156     * @return array|WP_Error Array of related-post summaries, or WP_Error on validation failure.
157     */
158    public static function get_related_posts( $input = null ) {
159        $input = is_array( $input ) ? $input : array();
160
161        $post_id = isset( $input['post_id'] ) ? (int) $input['post_id'] : 0;
162        if ( $post_id <= 0 ) {
163            return new WP_Error(
164                'jetpack_related_posts_missing_post_id',
165                __( 'A post_id is required to fetch related posts.', 'jetpack' )
166            );
167        }
168
169        $post = get_post( $post_id );
170        if ( null === $post || empty( $post->ID ) ) {
171            return new WP_Error(
172                'jetpack_related_posts_invalid_post_id',
173                __( 'Unknown post ID. Verify the post exists and is accessible.', 'jetpack' )
174            );
175        }
176
177        // Match the per-post gate the existing /wpcom/v2/related-posts/{id}
178        // endpoint uses: the broad `edit_posts` cap on permission_callback lets
179        // the ability appear in the agent menu, but the actual lookup is
180        // authorized only when the caller can edit this specific post.
181        if ( ! current_user_can( 'edit_post', $post->ID ) ) {
182            return new WP_Error(
183                'jetpack_related_posts_forbidden',
184                __( 'You are not allowed to fetch related posts for this post.', 'jetpack' )
185            );
186        }
187
188        if ( isset( $input['per_page'] ) && is_int( $input['per_page'] ) ) {
189            // per_page wins when both are supplied; schema enforces the 1..MAX_SIZE
190            // range, the clamp here is defense in depth for direct callers that
191            // bypass schema validation.
192            $size = max( 1, min( self::MAX_SIZE, $input['per_page'] ) );
193        } elseif ( isset( $input['size'] ) && is_int( $input['size'] ) ) {
194            $size = max( 1, min( self::MAX_SIZE, $input['size'] ) );
195        } else {
196            $size = self::DEFAULT_SIZE;
197        }
198
199        $args = array( 'size' => $size );
200
201        if ( isset( $input['post_type'] ) && is_string( $input['post_type'] ) && '' !== $input['post_type'] ) {
202            $args['post_type'] = $input['post_type'];
203        }
204
205        if ( isset( $input['exclude_post_ids'] ) && is_array( $input['exclude_post_ids'] ) ) {
206            $args['exclude_post_ids'] = array_values(
207                array_filter(
208                    array_map( 'intval', $input['exclude_post_ids'] ),
209                    static function ( $id ) {
210                        return $id > 0;
211                    }
212                )
213            );
214        }
215
216        $results = self::related_posts_instance()->get_for_post_id( $post->ID, $args );
217        if ( ! is_array( $results ) || array() === $results ) {
218            return array();
219        }
220
221        // Prime the post cache once so `get_post_type()` inside summarize_related_post
222        // doesn't trigger N individual lookups when the cache is cold.
223        _prime_post_caches( wp_list_pluck( $results, 'id' ), false, false );
224
225        $out = array();
226        foreach ( $results as $related ) {
227            $out[] = self::summarize_related_post( $related );
228        }
229        return $out;
230    }
231
232    /**
233     * Returns the Jetpack Related Posts raw instance, loading the class file lazily
234     * when it has not been included by the module's own load action yet.
235     *
236     * @return \Jetpack_RelatedPosts
237     */
238    private static function related_posts_instance() {
239        if ( ! class_exists( Jetpack_RelatedPosts::class, false ) ) {
240            require_once __DIR__ . '/../jetpack-related-posts.php';
241        }
242        return Jetpack_RelatedPosts::init_raw();
243    }
244
245    /**
246     * Reduce the rich Related Posts result to a high-signal summary.
247     *
248     * @param array $related Single related-post entry from get_for_post_id().
249     * @return array
250     */
251    private static function summarize_related_post( array $related ): array {
252        $id = isset( $related['id'] ) ? (int) $related['id'] : 0;
253
254        return array(
255            'id'        => $id,
256            'url'       => isset( $related['url'] ) ? (string) $related['url'] : '',
257            'title'     => isset( $related['title'] ) ? (string) $related['title'] : '',
258            'excerpt'   => isset( $related['excerpt'] ) ? (string) $related['excerpt'] : '',
259            'date'      => isset( $related['date'] ) ? (string) $related['date'] : '',
260            'post_type' => $id > 0 ? (string) get_post_type( $id ) : '',
261            'format'    => isset( $related['format'] ) && '' !== $related['format'] ? (string) $related['format'] : null,
262        );
263    }
264}