Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
90.85% covered (success)
90.85%
129 / 142
75.00% covered (warning)
75.00%
6 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
Related_Posts_Abilities
92.14% covered (success)
92.14%
129 / 140
75.00% covered (warning)
75.00%
6 / 8
35.59
0.00% covered (danger)
0.00%
0 / 1
 enabled_by_default
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
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     * {@inheritDoc}
40     */
41    protected static function enabled_by_default(): bool {
42        return true;
43    }
44
45    /**
46     * Returns the category slug this registrar owns.
47     */
48    public static function get_category_slug(): string {
49        return 'jetpack-related-posts';
50    }
51
52    /**
53     * Returns the category definition passed to wp_register_ability_category().
54     */
55    public static function get_category_definition(): array {
56        return array(
57            // "Jetpack" is a product name and should not be translated.
58            'label'       => 'Jetpack Related Posts',
59            'description' => __( 'Abilities for reading related posts.', 'jetpack' ),
60        );
61    }
62
63    /**
64     * Returns the abilities this registrar owns as a [ slug => spec ] map.
65     */
66    public static function get_abilities(): array {
67        $related_post_schema = array(
68            'type'       => 'object',
69            'properties' => array(
70                'id'        => array( 'type' => 'integer' ),
71                'url'       => array( 'type' => 'string' ),
72                'title'     => array( 'type' => 'string' ),
73                'excerpt'   => array( 'type' => 'string' ),
74                'date'      => array( 'type' => 'string' ),
75                'post_type' => array( 'type' => 'string' ),
76                'format'    => array( 'type' => array( 'string', 'null' ) ),
77            ),
78        );
79
80        return array(
81            'jetpack-related-posts/get-related-posts' => array(
82                'label'               => __( 'Get related posts', 'jetpack' ),
83                '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' ),
84                'input_schema'        => array(
85                    'type'                 => 'object',
86                    'required'             => array( 'post_id' ),
87                    'properties'           => array(
88                        'post_id'          => array(
89                            'type'        => 'integer',
90                            'description' => __( 'WordPress post ID to find related posts for. Must reference an existing post.', 'jetpack' ),
91                            'minimum'     => 1,
92                        ),
93                        'per_page'         => array(
94                            'type'        => 'integer',
95                            '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' ),
96                            'minimum'     => 1,
97                            'maximum'     => self::MAX_SIZE,
98                            'default'     => self::MAX_SIZE,
99                        ),
100                        'size'             => array(
101                            'type'        => 'integer',
102                            'description' => __( 'Deprecated alias for per_page. Defaults to 3 when per_page is omitted. Capped at 20.', 'jetpack' ),
103                            'minimum'     => 1,
104                            'maximum'     => self::MAX_SIZE,
105                            'default'     => self::DEFAULT_SIZE,
106                        ),
107                        'post_type'        => array(
108                            'type'        => 'string',
109                            'description' => __( 'Restrict matches to a single post type slug (e.g. "post", "page"). Defaults to the source post\'s type.', 'jetpack' ),
110                            'minLength'   => 1,
111                        ),
112                        'exclude_post_ids' => array(
113                            'type'        => 'array',
114                            'description' => __( 'Post IDs to exclude from the result.', 'jetpack' ),
115                            'items'       => array(
116                                'type'    => 'integer',
117                                'minimum' => 1,
118                            ),
119                            'default'     => array(),
120                        ),
121                    ),
122                    'additionalProperties' => false,
123                ),
124                'output_schema'       => array(
125                    'type'  => 'array',
126                    'items' => $related_post_schema,
127                ),
128                'execute_callback'    => array( __CLASS__, 'get_related_posts' ),
129                'permission_callback' => array( __CLASS__, 'can_view_related_posts' ),
130                'meta'                => array(
131                    'annotations'  => array(
132                        'readonly'    => true,
133                        'destructive' => false,
134                        'idempotent'  => true,
135                    ),
136                    'public'       => true,
137                    'show_in_rest' => true,
138                    'mcp'          => array(
139                        'public' => true,
140                        'type'   => 'tool', // default is already "tool", but can be explicit.
141                    ),
142                ),
143            ),
144        );
145    }
146
147    /**
148     * Permission gate for the ability menu.
149     *
150     * Returns true if the caller can edit any post — keeps the ability listed
151     * for agents that have at least one editable post. The actual per-post
152     * authorization runs inside `get_related_posts()` once the source post_id
153     * is known, mirroring the existing /wpcom/v2/related-posts/{id} endpoint.
154     */
155    public static function can_view_related_posts(): bool {
156        return current_user_can( 'edit_posts' );
157    }
158
159    /**
160     * Execute: return related posts for a given post.
161     *
162     * @param array|null $input Input matching the ability's input_schema.
163     * @return array|WP_Error Array of related-post summaries, or WP_Error on validation failure.
164     */
165    public static function get_related_posts( $input = null ) {
166        $input = is_array( $input ) ? $input : array();
167
168        $post_id = isset( $input['post_id'] ) ? (int) $input['post_id'] : 0;
169        if ( $post_id <= 0 ) {
170            return new WP_Error(
171                'jetpack_related_posts_missing_post_id',
172                __( 'A post_id is required to fetch related posts.', 'jetpack' )
173            );
174        }
175
176        $post = get_post( $post_id );
177        if ( null === $post || empty( $post->ID ) ) {
178            return new WP_Error(
179                'jetpack_related_posts_invalid_post_id',
180                __( 'Unknown post ID. Verify the post exists and is accessible.', 'jetpack' )
181            );
182        }
183
184        // Match the per-post gate the existing /wpcom/v2/related-posts/{id}
185        // endpoint uses: the broad `edit_posts` cap on permission_callback lets
186        // the ability appear in the agent menu, but the actual lookup is
187        // authorized only when the caller can edit this specific post.
188        if ( ! current_user_can( 'edit_post', $post->ID ) ) {
189            return new WP_Error(
190                'jetpack_related_posts_forbidden',
191                __( 'You are not allowed to fetch related posts for this post.', 'jetpack' )
192            );
193        }
194
195        if ( isset( $input['per_page'] ) && is_int( $input['per_page'] ) ) {
196            // per_page wins when both are supplied; schema enforces the 1..MAX_SIZE
197            // range, the clamp here is defense in depth for direct callers that
198            // bypass schema validation.
199            $size = max( 1, min( self::MAX_SIZE, $input['per_page'] ) );
200        } elseif ( isset( $input['size'] ) && is_int( $input['size'] ) ) {
201            $size = max( 1, min( self::MAX_SIZE, $input['size'] ) );
202        } else {
203            $size = self::DEFAULT_SIZE;
204        }
205
206        $args = array( 'size' => $size );
207
208        if ( isset( $input['post_type'] ) && is_string( $input['post_type'] ) && '' !== $input['post_type'] ) {
209            $args['post_type'] = $input['post_type'];
210        }
211
212        if ( isset( $input['exclude_post_ids'] ) && is_array( $input['exclude_post_ids'] ) ) {
213            $args['exclude_post_ids'] = array_values(
214                array_filter(
215                    array_map( 'intval', $input['exclude_post_ids'] ),
216                    static function ( $id ) {
217                        return $id > 0;
218                    }
219                )
220            );
221        }
222
223        $results = self::related_posts_instance()->get_for_post_id( $post->ID, $args );
224        if ( ! is_array( $results ) || array() === $results ) {
225            return array();
226        }
227
228        // Prime the post cache once so `get_post_type()` inside summarize_related_post
229        // doesn't trigger N individual lookups when the cache is cold.
230        _prime_post_caches( wp_list_pluck( $results, 'id' ), false, false );
231
232        $out = array();
233        foreach ( $results as $related ) {
234            $out[] = self::summarize_related_post( $related );
235        }
236        return $out;
237    }
238
239    /**
240     * Returns the Jetpack Related Posts raw instance, loading the class file lazily
241     * when it has not been included by the module's own load action yet.
242     *
243     * @return \Jetpack_RelatedPosts
244     */
245    private static function related_posts_instance() {
246        if ( ! class_exists( Jetpack_RelatedPosts::class, false ) ) {
247            require_once __DIR__ . '/../jetpack-related-posts.php';
248        }
249        return Jetpack_RelatedPosts::init_raw();
250    }
251
252    /**
253     * Reduce the rich Related Posts result to a high-signal summary.
254     *
255     * @param array $related Single related-post entry from get_for_post_id().
256     * @return array
257     */
258    private static function summarize_related_post( array $related ): array {
259        $id = isset( $related['id'] ) ? (int) $related['id'] : 0;
260
261        return array(
262            'id'        => $id,
263            'url'       => isset( $related['url'] ) ? (string) $related['url'] : '',
264            'title'     => isset( $related['title'] ) ? (string) $related['title'] : '',
265            'excerpt'   => isset( $related['excerpt'] ) ? (string) $related['excerpt'] : '',
266            'date'      => isset( $related['date'] ) ? (string) $related['date'] : '',
267            'post_type' => $id > 0 ? (string) get_post_type( $id ) : '',
268            'format'    => isset( $related['format'] ) && '' !== $related['format'] ? (string) $related['format'] : null,
269        );
270    }
271}