Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
69.89% covered (warning)
69.89%
195 / 279
33.33% covered (danger)
33.33%
5 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_REST_API_V3_Endpoint_Blogging_Prompts
70.65% covered (warning)
70.65%
195 / 276
33.33% covered (danger)
33.33%
5 / 15
176.11
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 register_routes
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
1
 get_items
15.38% covered (danger)
15.38%
2 / 13
0.00% covered (danger)
0.00%
0 / 1
8.45
 get_item
25.00% covered (danger)
25.00%
2 / 8
0.00% covered (danger)
0.00%
0 / 1
6.80
 modify_query
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
3
 map_date_query
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
6.05
 filter_sql
100.00% covered (success)
100.00%
33 / 33
100.00% covered (success)
100.00%
1 / 1
8
 prepare_item_for_response
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
240
 is_in_bloganuary
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_bloganuary_id
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 prepare_date_response
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
30
 get_collection_params
97.14% covered (success)
97.14%
34 / 35
0.00% covered (danger)
0.00%
0 / 1
4
 get_item_schema
100.00% covered (success)
100.00%
62 / 62
100.00% covered (success)
100.00%
1 / 1
1
 permissions_check
61.54% covered (warning)
61.54%
8 / 13
0.00% covered (danger)
0.00%
0 / 1
8.05
 build_answering_users_sample
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
42
1<?php
2/**
3 * Blogging prompts endpoint for wpcom/v3.
4 *
5 * @package automattic/jetpack
6 */
7
8use Automattic\Jetpack\Connection\Traits\WPCOM_REST_API_Proxy_Request;
9
10if ( ! defined( 'ABSPATH' ) ) {
11    exit( 0 );
12}
13
14/**
15 * REST API endpoint wpcom/v3/sites/%s/blogging-prompts.
16 */
17class WPCOM_REST_API_V3_Endpoint_Blogging_Prompts extends WP_REST_Posts_Controller {
18
19    use WPCOM_REST_API_Proxy_Request;
20
21    const TEMPLATE_BLOG_ID = 205876834;
22
23    /**
24     * Whether the endpoint is running on wpcom, or not.
25     *
26     * @var bool
27     */
28    public $is_wpcom;
29
30    /**
31     * Day of the year, from 1 to 366, and 0 representing no query.
32     *
33     * Used with yearless dates like `--12-20`, to get prompts by month and day, regardless of year.
34     *
35     * @var integer
36     */
37    public $day_of_year_query = 0;
38
39    /**
40     * A year used to force one prompt per day for a specific year.
41     *
42     * @var integer
43     */
44    public $force_year = 0;
45
46    /**
47     * Constructor.
48     */
49    public function __construct() {
50        $this->post_type                       = 'post';
51        $this->base_api_path                   = 'wpcom';
52        $this->version                         = 'v3';
53        $this->namespace                       = $this->base_api_path . '/' . $this->version;
54        $this->rest_base                       = 'blogging-prompts';
55        $this->wpcom_is_wpcom_only_endpoint    = true;
56        $this->wpcom_is_site_specific_endpoint = true;
57        $this->is_wpcom                        = defined( 'IS_WPCOM' ) && IS_WPCOM;
58
59        add_action( 'rest_api_init', array( $this, 'register_routes' ) );
60    }
61
62    /**
63     * Registers the routes for blogging prompts.
64     *
65     * @see register_rest_route()
66     */
67    public function register_routes() {
68        register_rest_route(
69            $this->namespace,
70            '/' . $this->rest_base,
71            array(
72                array(
73                    'methods'             => WP_REST_Server::READABLE,
74                    'callback'            => array( $this, 'get_items' ),
75                    'permission_callback' => array( $this, 'permissions_check' ),
76                    'args'                => $this->get_collection_params(),
77                ),
78                'schema' => array( $this, 'get_item_schema' ),
79            )
80        );
81
82        register_rest_route(
83            $this->namespace,
84            '/' . $this->rest_base . '/(?P<id>[\d]+)',
85            array(
86                'args'   => array(
87                    'id' => array(
88                        'description' => __( 'Unique identifier for the prompt.', 'jetpack' ),
89                        'type'        => 'integer',
90                    ),
91                ),
92                array(
93                    'methods'             => WP_REST_Server::READABLE,
94                    'callback'            => array( $this, 'get_item' ),
95                    'permission_callback' => array( $this, 'permissions_check' ),
96                ),
97                'schema' => array( $this, 'get_item_schema' ),
98            )
99        );
100    }
101
102    /**
103     * Retrieves a collection of blogging prompts.
104     *
105     * @param WP_REST_Request $request Full details about the request.
106     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
107     */
108    public function get_items( $request ) {
109        if ( ! $this->is_wpcom ) {
110            return $this->proxy_request_to_wpcom( $request, '', 'user', true );
111        }
112
113        if ( $request->get_param( 'force_year' ) ) {
114            $this->force_year = $request->get_param( 'force_year' );
115        }
116
117        switch_to_blog( self::TEMPLATE_BLOG_ID );
118        add_action( 'pre_get_posts', array( $this, 'modify_query' ) );
119        add_filter( 'posts_clauses', array( $this, 'filter_sql' ), 10, 2 );
120        $items = parent::get_items( $request );
121        remove_filter( 'posts_clauses', array( $this, 'filter_sql' ) );
122        remove_action( 'pre_get_posts', array( $this, 'modify_query' ) );
123        restore_current_blog();
124
125        // Reset so a later query in the same request can never inherit this state.
126        $this->day_of_year_query = 0;
127
128        return $items;
129    }
130
131    /**
132     * Retrieves a single blogging prompt.
133     *
134     * @param WP_REST_Request $request Full details about the request.
135     * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
136     */
137    public function get_item( $request ) {
138        if ( ! $this->is_wpcom ) {
139            return $this->proxy_request_to_wpcom( $request, $request->get_param( 'id' ), 'user', true );
140        }
141
142        if ( $request->get_param( 'force_year' ) ) {
143            $this->force_year = $request->get_param( 'force_year' );
144        }
145
146        switch_to_blog( self::TEMPLATE_BLOG_ID );
147        $item = parent::get_item( $request );
148        restore_current_blog();
149
150        return $item;
151    }
152
153    /**
154     * Modify the posts query using the {@see 'pre_get_posts'} hook.
155     *
156     * @param WP_Query $wp_query The WP_Query instance (passed by reference).
157     */
158    public function modify_query( &$wp_query ) {
159        // parent::get_items() renders each prompt while this hook is still attached,
160        // and rendering can spawn nested WP_Querys (e.g. Gutenberg's wp_global_styles
161        // lookup), so only ever touch the prompts query itself.
162        if ( $this->post_type !== $wp_query->get( 'post_type' ) ) {
163            return;
164        }
165
166        $date_query = $wp_query->get( 'date_query' );
167
168        if ( is_array( $date_query ) ) {
169            $wp_query->set( 'date_query', array_map( array( $this, 'map_date_query' ), $date_query ) );
170            // Mark the query so filter_sql() only modifies this one.
171            $wp_query->set( 'jetpack_blogging_prompts', true );
172        }
173    }
174
175    /**
176     * Modify date_query items when querying prompts.
177     *
178     * @link https://developer.wordpress.org/reference/classes/WP_Query/#date-parameters
179     *
180     * @param  array|string|null $date_query Date query.
181     * @return array|string|null             Modified date query.
182     */
183    public function map_date_query( $date_query ) {
184        if ( isset( $date_query['after'] ) ) {
185            // `after` date queries should include posts on the specified date, so force `inclusive` queries.
186            $date_query['inclusive'] = true;
187
188            // If using a "year-less" date, e.g. `--03-16`, override the date_query, and prepare to modify sql manually.
189            // `after` should be a date string when making API requests, rather than an array.
190            if ( is_string( $date_query['after'] ) && str_starts_with( $date_query['after'], '-' ) ) {
191                // Use the same year as filter_sql(), or leap years shift the day by one after Feb 28th.
192                $year = $this->force_year ? (int) $this->force_year : (int) wp_date( 'Y' );
193                $date = date_create_from_format( 'Y--m-d', sprintf( '%04d', $year ) . $date_query['after'] );
194
195                if ( false !== $date ) {
196                    // PHP day of the year starts with 0; normalize to match SQL DAYOFTHEYEAR which starts with 1.
197                    $this->day_of_year_query = $date->format( 'z' ) + 1;
198
199                    // Unset the date query, since we'll by modifying the SQL manually.
200                    return null;
201                }
202            }
203        }
204
205        return $date_query;
206    }
207
208    /**
209     * Modify post sql for custom date ordering using the {@see 'posts_clauses'} hook.
210     *
211     * @param array         $clauses SQL clauses for the current query.
212     * @param WP_Query|null $query   The WP_Query instance being filtered.
213     * @return array                 Modified SQL clauses.
214     */
215    public function filter_sql( $clauses, $query = null ) {
216        global $wpdb;
217        if ( ! $query instanceof WP_Query || ! $query->get( 'jetpack_blogging_prompts' ) ) {
218            return $clauses;
219        }
220        if ( $this->day_of_year_query > 0 ) {
221            $day  = $this->day_of_year_query;
222            $year = $this->force_year ? $this->force_year : wp_date( 'Y' );
223
224            // Grab the current sort order, `ASC` or `DESC`, so we can reuse it.
225            $exploded = explode( ' ', $clauses['orderby'] );
226            $order    = end( $exploded );
227
228            // Calculate the day of year for each prompt, from 1 to 366, but use the current year so that prompts published
229            // during leap years have the correct day for non-leap years.
230            $fields = $clauses['fields'] . $wpdb->prepare( ", DAYOFYEAR(CONCAT(%d, DATE_FORMAT({$wpdb->posts}.post_date, '-%%m-%%d'))) AS day_of_year", $year );
231
232            // When it's not a leap year, exclude posts used for Feb 29th. DAYOFYEAR will return null for Feb 29th on non-leap years.
233            $where = $clauses['where'] . $wpdb->prepare( " AND DAYOFYEAR(CONCAT(%d, DATE_FORMAT({$wpdb->posts}.post_date, '-%%m-%%d'))) IS NOT NULL", $year );
234
235            // Order posts regardless of year: get a list of posts for each day,
236            // starting with the query date through the end of the year, then from the start of the year through the day before.
237            $orderby = $wpdb->prepare(
238                'CASE ' .
239                    'WHEN day_of_year < %d ' .
240                    // Push posts from the beginning of the year until the day before to the end.
241                    'THEN day_of_year + 366 ' .
242                    // Otherwise order posts from the query date through the end of the year.
243                    'ELSE day_of_year ' .
244                'END' .
245                // Sort posts for the same day by year, in asc or desc order.
246                // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- order string cannot be escaped.
247                ", YEAR({$wpdb->posts}.post_date) " . ( 'DESC' === $order ? 'DESC' : 'ASC' ),
248                $day
249            );
250
251            if ( $this->force_year ) {
252                // If we're forcing the year, group by day of year, so that we only get one prompt per day.
253                $clauses['groupby'] = 'day_of_year';
254
255                // Ensure we get either to newest or oldest prompt for each day of the year, depending on the sort order.
256                // GROUP BY runs and collects the prompts for each day of the year before ORDER BY is run, so we first need to use MAX/MIN on post_date
257                // to find the most recent/oldest prompt for each day and join the results to the main query.
258                $clauses['join'] = $wpdb->prepare(
259                    'INNER JOIN (' .
260                        // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL function cannot be escaped.
261                        'SELECT ' . ( 'DESC' === $order ? 'MAX' : 'MIN' ) . "({$wpdb->posts}.post_date) AS post_date, DAYOFYEAR(CONCAT(%d, DATE_FORMAT(post_date, '-%%m-%%d'))) AS day_of_year " .
262                        "FROM {$wpdb->posts} " .
263                        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- reuses unmodified existing clause.
264                        "WHERE 1=1 {$clauses['where']} " .
265                        'GROUP BY day_of_year' .
266                    ") AS newest_prompts ON {$wpdb->posts}.post_date = newest_prompts.post_date",
267                    $year
268                );
269            }
270
271            $clauses['fields']  = $fields;
272            $clauses['where']   = $where;
273            $clauses['orderby'] = $orderby;
274        }
275
276        return $clauses;
277    }
278
279    /**
280     * Prepares a single blogging prompt output for response.
281     *
282     * @param WP_Post         $prompt  Post object.
283     * @param WP_REST_Request $request Request object.
284     * @return WP_REST_Response        Response object.
285     */
286    public function prepare_item_for_response( $prompt, $request ) {
287        require_once WP_CONTENT_DIR . '/lib/blogging-prompts/answers.php';
288        require_once WP_CONTENT_DIR . '/lib/blogging-prompts/utils.php';
289
290        $fields = $this->get_fields_for_response( $request );
291
292        // Base fields for every post.
293        $data = array();
294
295        if ( rest_is_field_included( 'id', $fields ) ) {
296            $data['id'] = $prompt->ID;
297        }
298
299        if ( rest_is_field_included( 'date', $fields ) ) {
300            $data['date'] = $this->prepare_date_response( $prompt->post_date_gmt );
301        }
302
303        if ( rest_is_field_included( 'label', $fields ) ) {
304            if ( $this->is_in_bloganuary( $prompt->post_date_gmt ) ) {
305                $data['label'] = __( 'Bloganuary writing prompt', 'jetpack' );
306            } else {
307                $data['label'] = __( 'Daily writing prompt', 'jetpack' );
308            }
309        }
310
311        if ( rest_is_field_included( 'text', $fields ) ) {
312            $text = \BloggingPrompts\prompt_without_blocks( $prompt->post_content );
313            // Allow translating a variable, since this text is imported from bloggingpromptstemplates.wordpress.com for translation.
314            $translated_text = __( $text, 'jetpack' ); // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
315            $data['text']    = wp_kses( $translated_text, wp_kses_allowed_html( 'post' ) );
316        }
317
318        if ( rest_is_field_included( 'attribution', $fields ) ) {
319            $data['attribution'] = esc_html( get_post_meta( $prompt->ID, 'blogging_prompts_attribution', true ) );
320        }
321
322        // Will always be false when requesting as blog.
323        if ( rest_is_field_included( 'answered', $fields ) ) {
324            $data['answered'] = (bool) \A8C\BloggingPrompts\Answers::is_answered_by_user( $prompt->ID, get_current_user_id() );
325        }
326
327        if ( rest_is_field_included( 'answered_users_count', $fields ) ) {
328            $data['answered_users_count'] = (int) \A8C\BloggingPrompts\Answers::get_count( $prompt->ID );
329        }
330
331        if ( rest_is_field_included( 'answered_users_sample', $fields ) ) {
332            $data['answered_users_sample'] = $this->build_answering_users_sample( $prompt->ID );
333        }
334
335        if ( rest_is_field_included( 'answered_link', $fields ) ) {
336            if ( $this->is_in_bloganuary( $prompt->post_date_gmt ) ) {
337                $bloganuary_id         = $this->get_bloganuary_id( $prompt->post_date_gmt );
338                $data['answered_link'] = esc_url( "https://wordpress.com/tag/{$bloganuary_id}" );
339            } else {
340                $data['answered_link'] = esc_url( "https://wordpress.com/tag/dailyprompt-{$prompt->ID}" );
341            }
342        }
343
344        if ( rest_is_field_included( 'answered_link_text', $fields ) ) {
345            $data['answered_link_text'] = __( 'View all responses', 'jetpack' );
346        }
347
348        if ( $this->is_in_bloganuary( $prompt->post_date_gmt ) && rest_is_field_included( 'bloganuary_id', $fields ) ) {
349            $data['bloganuary_id'] = $this->get_bloganuary_id( $prompt->post_date_gmt );
350        }
351
352        return $data;
353    }
354
355    /**
356     * Return true if the post is in "Bloganuary"
357     *
358     * @param string $post_date_gmt Unused - Post date in GMT.
359     * @return bool Always returns false as Bloganuary is disabled.
360     */
361    protected function is_in_bloganuary( $post_date_gmt ) { //phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
362
363        /*
364        Disable for January 2025 and beyond (see https://wp.me/p5uIfZ-gxX).
365            Previously, this method would check if the post was published in January:
366            - Extract month from post_date_gmt -- $post_month = gmdate( 'm', strtotime( $post_date_gmt ) );
367            - Return true if month was '01' -- return $post_month === '01';
368        */
369        return false;
370    }
371
372    /**
373     * Return the bloganuary id of the form `bloganuary-yyyy-dd`
374     *
375     * @param string $post_date_gmt Post date in GMT.
376     * @return string Bloganuary id.
377     */
378    protected function get_bloganuary_id( $post_date_gmt ) {
379        $post_year_day = gmdate( 'Y-d', strtotime( $post_date_gmt ) );
380        if ( $this->force_year ) {
381            $post_year_day = $this->force_year . '-' . gmdate( 'd', strtotime( $post_date_gmt ) );
382        }
383        return 'bloganuary-' . $post_year_day;
384    }
385
386    /**
387     * Format a date for a blogging prompt, omiting the time.
388     *
389     * @param string $date_gmt Publish datetime of the prompt in GMT, i.e. 0000-00-00 00:00:00.
390     * @param string $date     Publish datetime of the prompt, i.e. 0000-00-00 00:00:00.
391     * @return string Publish date of the prompt in YYYY-MM-DD format.
392     */
393    public function prepare_date_response( $date_gmt, $date = null ) {
394        $post_date = $date ? $date : $date_gmt;
395        $date_obj  = date_create( $post_date );
396
397        if ( $this->force_year ) {
398            $date_obj->setDate( $this->force_year, (int) $date_obj->format( 'n' ), (int) $date_obj->format( 'j' ) );
399
400            // If ascending by day of year, go to the next year when we pass the last day of the year.
401            if ( $date_obj->format( 'm-d' ) === '12-31' ) {
402                $this->force_year += 1;
403            }
404        }
405
406        return false !== $date_obj ? $date_obj->format( 'Y-m-d' ) : substr( $post_date, 0, 10 );
407    }
408
409    /**
410     * Retrieves the query params for blogging prompt collections.
411     *
412     * @return array Query parameters for the collection.
413     */
414    public function get_collection_params() {
415        $parent_args = parent::get_collection_params();
416
417        $args = array(
418            // Modify date args so that will except a YYYY-MM-DD without a time.
419            'after'      => array(
420                'description'       => __( 'Show prompts following a given date.', 'jetpack' ),
421                'type'              => 'string',
422                'validate_callback' => function ( $param ) {
423                    // Allow month and day without year, e.g. `--02-28`
424                    if ( str_starts_with( $param, '-' ) ) {
425                        return false !== date_create_from_format( '--m-d', $param );
426                    }
427
428                    return false !== date_create( $param );
429                },
430            ),
431            'before'     => array(
432                'description'       => __( 'Show prompts before a given date.', 'jetpack' ),
433                'type'              => 'string',
434                'validate_callback' => function ( $param ) {
435                    return false !== date_create( $param );
436                },
437            ),
438            'force_year' => array(
439                'description'       => __( 'Force the returned prompts to be for a specific year. Returns only one prompt for each day.', 'jetpack' ),
440                'type'              => 'integer',
441                'validate_callback' => function ( $param ) {
442                    return is_numeric( $param ) && intval( $param ) > 0 && intval( $param ) < 9999;
443                },
444            ),
445        );
446
447        $args['exclude']          = $parent_args['exclude'];
448        $args['include']          = $parent_args['include'];
449        $args['page']             = $parent_args['page'];
450        $args['per_page']         = $parent_args['per_page'];
451        $args['order']            = $parent_args['order'];
452        $args['order']['default'] = 'asc';
453        $args['orderby']          = $parent_args['orderby'];
454        $args['search']           = $parent_args['search'];
455
456        return $args;
457    }
458
459    /**
460     * Retrieves the blogging prompt's schema, conforming to JSON Schema.
461     *
462     * @return array Item schema data.
463     */
464    public function get_item_schema() {
465        return array(
466            '$schema'    => 'http://json-schema.org/draft-04/schema#',
467            'title'      => 'blogging-prompt',
468            'type'       => 'object',
469            'properties' => array(
470                'id'                    => array(
471                    'description' => __( 'Unique identifier for the post.', 'jetpack' ),
472                    'type'        => 'integer',
473                ),
474                'date'                  => array(
475                    'description' => __( "The date the post was published, in the site's timezone.", 'jetpack' ),
476                    'type'        => 'string',
477                ),
478                'label'                 => array(
479                    'description' => __( 'Label for the prompt.', 'jetpack' ),
480                    'type'        => 'string',
481                ),
482                'text'                  => array(
483                    'description' => __( 'The text of the prompt. May include html tags like <em>.', 'jetpack' ),
484                    'type'        => 'string',
485                ),
486                'attribution'           => array(
487                    'description' => __( 'Source of the prompt, if known.', 'jetpack' ),
488                    'type'        => 'string',
489                ),
490                'answered'              => array(
491                    'description' => __( 'Whether the user has answered the prompt.', 'jetpack' ),
492                    'type'        => 'boolean',
493                ),
494                'answered_users_count'  => array(
495                    'description' => __( 'Number of users who have answered the prompt.', 'jetpack' ),
496                    'type'        => 'integer',
497                ),
498                'answered_users_sample' => array(
499                    'description' => __( 'Sample of users who have answered the prompt.', 'jetpack' ),
500                    'type'        => 'array',
501                    'items'       => array(
502                        'type'       => 'object',
503                        'properties' => array(
504                            'avatar' => array(
505                                'description' => __( "Gravatar URL for the user's avatar image.", 'jetpack' ),
506                                'type'        => 'string',
507                                'format'      => 'uri',
508                            ),
509                        ),
510                    ),
511                ),
512                'answered_link'         => array(
513                    'description' => __( 'Link to answers for the prompt.', 'jetpack' ),
514                    'type'        => 'string',
515                    'format'      => 'uri',
516                ),
517                'answered_link_text'    => array(
518                    'description' => __( 'Text for the link to answers for the prompt.', 'jetpack' ),
519                    'type'        => 'string',
520                ),
521                'bloganuary_id'         => array(
522                    'description' => __( 'Id used by the bloganuary promotion', 'jetpack' ),
523                    'type'        => 'string',
524                ),
525            ),
526        );
527    }
528
529    /**
530     * Checks if a given request has access to read blogging prompts for a site.
531     *
532     * @return true|WP_Error True if the request has read access, WP_Error object otherwise.
533     */
534    public function permissions_check() {
535        if ( current_user_can( 'edit_posts' ) ) {
536            return true;
537        }
538
539        // Allow "as blog" requests to wpcom so users without accounts can insert the Writing prompt block in the editor.
540        if ( $this->is_wpcom && is_jetpack_site( get_current_blog_id() ) ) {
541            if ( ! class_exists( 'WPCOM_REST_API_V2_Endpoint_Jetpack_Auth' ) ) {
542                require_once dirname( __DIR__ ) . '/rest-api-plugins/endpoints/jetpack-auth.php';
543            }
544
545            $jp_auth_endpoint = new WPCOM_REST_API_V2_Endpoint_Jetpack_Auth();
546            if ( true === $jp_auth_endpoint->is_jetpack_authorized_for_site() ) {
547                return true;
548            }
549        }
550
551        return new WP_Error(
552            'rest_cannot_read_prompts',
553            __( 'Sorry, you are not allowed to access blogging prompts on this site.', 'jetpack' ),
554            array( 'status' => rest_authorization_required_code() )
555        );
556    }
557
558    /**
559     * Creates a sample of users who have answered a blogging prompt.
560     *
561     * @param int $prompt_id Prompt ID.
562     * @return array List of users, including a gravatar url for each user.
563     */
564    protected function build_answering_users_sample( $prompt_id ) {
565        $results = \A8C\BloggingPrompts\Answers::get_sample_users_by( $prompt_id );
566
567        if ( ! $results ) {
568            return array();
569        }
570
571        $users = array();
572
573        foreach ( $results as $user ) {
574            $url = wpcom_get_avatar_url( $user->user_id, 96, 'identicon', false );
575            if ( has_gravatar( $user->user_id ) && ! empty( $url[0] ) && ! is_wp_error( $url[0] ) ) {
576                $users[] = array(
577                    'avatar' => (string) esc_url_raw( htmlspecialchars_decode( $url[0], ENT_COMPAT ) ),
578                );
579            }
580        }
581
582        return array_slice( $users, 0, 3 );
583    }
584}
585
586wpcom_rest_api_v2_load_plugin( 'WPCOM_REST_API_V3_Endpoint_Blogging_Prompts' );