PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3
Jetpack – WP Security, Backup, Speed, & Growth v16.3
16.3 16.3-beta 16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 All 508 releases
← All changes | _inc/lib/core-api/wpcom-endpoints/class-wpcom-rest-api-v3-endpoint-blogging-prompts.php +149 -59 12.1.3 → 16.3 View file →
@@ -4,15 +4,21 @@
4 4 *
5 5 * @package automattic/jetpack
6 6 */
7 7
8 -use Automattic\Jetpack\Connection\Client;
9 -use Automattic\Jetpack\Connection\Manager;
8 +use Automattic\Jetpack\Connection\Traits\WPCOM_REST_API_Proxy_Request;
10 9
10 +if ( ! defined( 'ABSPATH' ) ) {
11 + exit( 0 );
12 +}
13 +
11 14 /**
12 15 * REST API endpoint wpcom/v3/sites/%s/blogging-prompts.
13 16 */
14 17 class WPCOM_REST_API_V3_Endpoint_Blogging_Prompts extends WP_REST_Posts_Controller {
18 +
19 + use WPCOM_REST_API_Proxy_Request;
20 +
15 21 const TEMPLATE_BLOG_ID = 205876834;
16 22
17 23 /**
18 24 * Whether the endpoint is running on wpcom, or not.
@@ -30,13 +36,22 @@
30 36 */
31 37 public $day_of_year_query = 0;
32 38
33 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 + /**
34 47 * Constructor.
35 48 */
36 49 public function __construct() {
37 50 $this->post_type = 'post';
38 - $this->namespace = 'wpcom/v3';
51 + $this->base_api_path = 'wpcom';
52 + $this->version = 'v3';
53 + $this->namespace = $this->base_api_path . '/' . $this->version;
39 54 $this->rest_base = 'blogging-prompts';
40 55 $this->wpcom_is_wpcom_only_endpoint = true;
41 56 $this->wpcom_is_site_specific_endpoint = true;
42 57 $this->is_wpcom = defined( 'IS_WPCOM' ) && IS_WPCOM;
@@ -91,19 +106,26 @@
91 106 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
92 107 */
93 108 public function get_items( $request ) {
94 109 if ( ! $this->is_wpcom ) {
95 - return $this->proxy_request_to_wpcom( $request );
110 + return $this->proxy_request_to_wpcom( $request, '', 'user', true );
96 111 }
97 112
113 + if ( $request->get_param( 'force_year' ) ) {
114 + $this->force_year = $request->get_param( 'force_year' );
115 + }
116 +
98 117 switch_to_blog( self::TEMPLATE_BLOG_ID );
99 118 add_action( 'pre_get_posts', array( $this, 'modify_query' ) );
100 - add_filter( 'posts_clauses', array( $this, 'filter_sql' ) );
119 + add_filter( 'posts_clauses', array( $this, 'filter_sql' ), 10, 2 );
101 120 $items = parent::get_items( $request );
102 121 remove_filter( 'posts_clauses', array( $this, 'filter_sql' ) );
103 122 remove_action( 'pre_get_posts', array( $this, 'modify_query' ) );
104 123 restore_current_blog();
105 124
125 + // Reset so a later query in the same request can never inherit this state.
126 + $this->day_of_year_query = 0;
127 +
106 128 return $items;
107 129 }
108 130
109 131 /**
@@ -113,11 +135,15 @@
113 135 * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
114 136 */
115 137 public function get_item( $request ) {
116 138 if ( ! $this->is_wpcom ) {
117 - return $this->proxy_request_to_wpcom( $request, $request->get_param( 'id' ) );
139 + return $this->proxy_request_to_wpcom( $request, $request->get_param( 'id' ), 'user', true );
118 140 }
119 141
142 + if ( $request->get_param( 'force_year' ) ) {
143 + $this->force_year = $request->get_param( 'force_year' );
144 + }
145 +
120 146 switch_to_blog( self::TEMPLATE_BLOG_ID );
121 147 $item = parent::get_item( $request );
122 148 restore_current_blog();
123 149
@@ -129,14 +155,22 @@
129 155 *
130 156 * @param WP_Query $wp_query The WP_Query instance (passed by reference).
131 157 */
132 158 public function modify_query( &$wp_query ) {
133 - if ( is_array( $wp_query->query_vars['date_query'] ) ) {
134 - $wp_query->query_vars['date_query'] = array_map(
135 - array( $this, 'map_date_query' ),
136 - $wp_query->query_vars['date_query']
137 - );
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;
138 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 + }
139 173 }
140 174
141 175 /**
142 176 * Modify date_query items when querying prompts.
@@ -152,9 +186,9 @@
152 186 $date_query['inclusive'] = true;
153 187
154 188 // If using a "year-less" date, e.g. `--03-16`, override the date_query, and prepare to modify sql manually.
155 189 // `after` should be a date string when making API requests, rather than an array.
156 - if ( is_string( $date_query['after'] ) && 0 === strpos( $date_query['after'], '-' ) ) {
190 + if ( is_string( $date_query['after'] ) && str_starts_with( $date_query['after'], '-' ) ) {
157 191 $date = date_create_from_format( '--m-d', $date_query['after'] );
158 192
159 193 if ( false !== $date ) {
160 194 // PHP day of the year starts with 0; normalize to match SQL DAYOFTHEYEAR which starts with 1.
@@ -171,26 +205,31 @@
171 205
172 206 /**
173 207 * Modify post sql for custom date ordering using the {@see 'posts_clauses'} hook.
174 208 *
175 - * @param array $clauses SQL clauses for the current query.
176 - * @return array Modified SQL clauses.
209 + * @param array $clauses SQL clauses for the current query.
210 + * @param WP_Query|null $query The WP_Query instance being filtered.
211 + * @return array Modified SQL clauses.
177 212 */
178 - public function filter_sql( $clauses ) {
213 + public function filter_sql( $clauses, $query = null ) {
179 214 global $wpdb;
215 + if ( ! $query instanceof WP_Query || ! $query->get( 'jetpack_blogging_prompts' ) ) {
216 + return $clauses;
217 + }
180 218 if ( $this->day_of_year_query > 0 ) {
181 - $day = $this->day_of_year_query;
182 - $current_year = wp_date( 'Y' );
219 + $day = $this->day_of_year_query;
220 + $year = $this->force_year ? $this->force_year : wp_date( 'Y' );
183 221
184 222 // Grab the current sort order, `ASC` or `DESC`, so we can reuse it.
185 - $order = end( explode( ' ', $clauses['orderby'] ) );
223 + $exploded = explode( ' ', $clauses['orderby'] );
224 + $order = end( $exploded );
186 225
187 226 // Calculate the day of year for each prompt, from 1 to 366, but use the current year so that prompts published
188 227 // during leap years have the correct day for non-leap years.
189 - $fields = $clauses['fields'] . $wpdb->prepare( ", DAYOFYEAR(CONCAT(%d, DATE_FORMAT({$wpdb->posts}.post_date, '-%%m-%%d'))) AS day_of_year", $current_year );
228 + $fields = $clauses['fields'] . $wpdb->prepare( ", DAYOFYEAR(CONCAT(%d, DATE_FORMAT({$wpdb->posts}.post_date, '-%%m-%%d'))) AS day_of_year", $year );
190 229
191 230 // When it's not a leap year, exclude posts used for Feb 29th. DAYOFYEAR will return null for Feb 29th on non-leap years.
192 - $where = $clauses['where'] . $wpdb->prepare( " AND DAYOFYEAR(CONCAT(%d, DATE_FORMAT({$wpdb->posts}.post_date, '-%%m-%%d'))) IS NOT NULL", $current_year );
231 + $where = $clauses['where'] . $wpdb->prepare( " AND DAYOFYEAR(CONCAT(%d, DATE_FORMAT({$wpdb->posts}.post_date, '-%%m-%%d'))) IS NOT NULL", $year );
193 232
194 233 // Order posts regardless of year: get a list of posts for each day,
195 234 // starting with the query date through the end of the year, then from the start of the year through the day before.
196 235 $orderby = $wpdb->prepare(
@@ -206,8 +245,28 @@
206 245 ", YEAR({$wpdb->posts}.post_date) " . ( 'DESC' === $order ? 'DESC' : 'ASC' ),
207 246 $day
208 247 );
209 248
249 + if ( $this->force_year ) {
250 + // If we're forcing the year, group by day of year, so that we only get one prompt per day.
251 + $clauses['groupby'] = 'day_of_year';
252 +
253 + // Ensure we get either to newest or oldest prompt for each day of the year, depending on the sort order.
254 + // 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
255 + // to find the most recent/oldest prompt for each day and join the results to the main query.
256 + $clauses['join'] = $wpdb->prepare(
257 + 'INNER JOIN (' .
258 + // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- SQL function cannot be escaped.
259 + '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 " .
260 + "FROM {$wpdb->posts} " .
261 + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- reuses unmodified existing clause.
262 + "WHERE 1=1 {$clauses['where']} " .
263 + 'GROUP BY day_of_year' .
264 + ") AS newest_prompts ON {$wpdb->posts}.post_date = newest_prompts.post_date",
265 + $year
266 + );
267 + }
268 +
210 269 $clauses['fields'] = $fields;
211 270 $clauses['where'] = $where;
212 271 $clauses['orderby'] = $orderby;
213 272 }
@@ -239,9 +298,13 @@
239 298 $data['date'] = $this->prepare_date_response( $prompt->post_date_gmt );
240 299 }
241 300
242 301 if ( rest_is_field_included( 'label', $fields ) ) {
243 - $data['label'] = __( 'Daily writing prompt', 'jetpack' );
302 + if ( $this->is_in_bloganuary( $prompt->post_date_gmt ) ) {
303 + $data['label'] = __( 'Bloganuary writing prompt', 'jetpack' );
304 + } else {
305 + $data['label'] = __( 'Daily writing prompt', 'jetpack' );
306 + }
244 307 }
245 308
246 309 if ( rest_is_field_included( 'text', $fields ) ) {
247 310 $text = \BloggingPrompts\prompt_without_blocks( $prompt->post_content );
@@ -267,9 +330,14 @@
267 330 $data['answered_users_sample'] = $this->build_answering_users_sample( $prompt->ID );
268 331 }
269 332
270 333 if ( rest_is_field_included( 'answered_link', $fields ) ) {
271 - $data['answered_link'] = esc_url( "https://wordpress.com/tag/dailyprompt-{$prompt->ID}" );
334 + if ( $this->is_in_bloganuary( $prompt->post_date_gmt ) ) {
335 + $bloganuary_id = $this->get_bloganuary_id( $prompt->post_date_gmt );
336 + $data['answered_link'] = esc_url( "https://wordpress.com/tag/{$bloganuary_id}" );
337 + } else {
338 + $data['answered_link'] = esc_url( "https://wordpress.com/tag/dailyprompt-{$prompt->ID}" );
339 + }
272 340 }
273 341
274 342 if ( rest_is_field_included( 'answered_link_text', $fields ) ) {
275 343 $data['answered_link_text'] = __( 'View all responses', 'jetpack' );
@@ -274,12 +342,47 @@
274 342 if ( rest_is_field_included( 'answered_link_text', $fields ) ) {
275 343 $data['answered_link_text'] = __( 'View all responses', 'jetpack' );
276 344 }
277 345
346 + if ( $this->is_in_bloganuary( $prompt->post_date_gmt ) && rest_is_field_included( 'bloganuary_id', $fields ) ) {
347 + $data['bloganuary_id'] = $this->get_bloganuary_id( $prompt->post_date_gmt );
348 + }
349 +
278 350 return $data;
279 351 }
280 352
281 353 /**
354 + * Return true if the post is in "Bloganuary"
355 + *
356 + * @param string $post_date_gmt Unused - Post date in GMT.
357 + * @return bool Always returns false as Bloganuary is disabled.
358 + */
359 + protected function is_in_bloganuary( $post_date_gmt ) { //phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
360 +
361 + /*
362 + Disable for January 2025 and beyond (see https://wp.me/p5uIfZ-gxX).
363 + Previously, this method would check if the post was published in January:
364 + - Extract month from post_date_gmt -- $post_month = gmdate( 'm', strtotime( $post_date_gmt ) );
365 + - Return true if month was '01' -- return $post_month === '01';
366 + */
367 + return false;
368 + }
369 +
370 + /**
371 + * Return the bloganuary id of the form `bloganuary-yyyy-dd`
372 + *
373 + * @param string $post_date_gmt Post date in GMT.
374 + * @return string Bloganuary id.
375 + */
376 + protected function get_bloganuary_id( $post_date_gmt ) {
377 + $post_year_day = gmdate( 'Y-d', strtotime( $post_date_gmt ) );
378 + if ( $this->force_year ) {
379 + $post_year_day = $this->force_year . '-' . gmdate( 'd', strtotime( $post_date_gmt ) );
380 + }
381 + return 'bloganuary-' . $post_year_day;
382 + }
383 +
384 + /**
282 385 * Format a date for a blogging prompt, omiting the time.
283 386 *
284 387 * @param string $date_gmt Publish datetime of the prompt in GMT, i.e. 0000-00-00 00:00:00.
285 388 * @param string $date Publish datetime of the prompt, i.e. 0000-00-00 00:00:00.
@@ -288,8 +391,17 @@
288 391 public function prepare_date_response( $date_gmt, $date = null ) {
289 392 $post_date = $date ? $date : $date_gmt;
290 393 $date_obj = date_create( $post_date );
291 394
395 + if ( $this->force_year ) {
396 + $date_obj->setDate( $this->force_year, (int) $date_obj->format( 'n' ), (int) $date_obj->format( 'j' ) );
397 +
398 + // If ascending by day of year, go to the next year when we pass the last day of the year.
399 + if ( $date_obj->format( 'm-d' ) === '12-31' ) {
400 + $this->force_year += 1;
401 + }
402 + }
403 +
292 404 return false !== $date_obj ? $date_obj->format( 'Y-m-d' ) : substr( $post_date, 0, 10 );
293 405 }
294 406
295 407 /**
@@ -301,14 +413,14 @@
301 413 $parent_args = parent::get_collection_params();
302 414
303 415 $args = array(
304 416 // Modify date args so that will except a YYYY-MM-DD without a time.
305 - 'after' => array(
417 + 'after' => array(
306 418 'description' => __( 'Show prompts following a given date.', 'jetpack' ),
307 419 'type' => 'string',
308 420 'validate_callback' => function ( $param ) {
309 - // Allow month and date without year, e.g. `--02-28`
310 - if ( strpos( $param, '-' ) === 0 ) {
421 + // Allow month and day without year, e.g. `--02-28`
422 + if ( str_starts_with( $param, '-' ) ) {
311 423 return false !== date_create_from_format( '--m-d', $param );
312 424 }
313 425
314 426 return false !== date_create( $param );
@@ -313,9 +425,9 @@
313 425
314 426 return false !== date_create( $param );
315 427 },
316 428 ),
317 - 'before' => array(
429 + 'before' => array(
318 430 'description' => __( 'Show prompts before a given date.', 'jetpack' ),
319 431 'type' => 'string',
320 432 'validate_callback' => function ( $param ) {
321 433 return false !== date_create( $param );
@@ -320,8 +432,15 @@
320 432 'validate_callback' => function ( $param ) {
321 433 return false !== date_create( $param );
322 434 },
323 435 ),
436 + 'force_year' => array(
437 + 'description' => __( 'Force the returned prompts to be for a specific year. Returns only one prompt for each day.', 'jetpack' ),
438 + 'type' => 'integer',
439 + 'validate_callback' => function ( $param ) {
440 + return is_numeric( $param ) && intval( $param ) > 0 && intval( $param ) < 9999;
441 + },
442 + ),
324 443 );
325 444
326 445 $args['exclude'] = $parent_args['exclude'];
327 446 $args['include'] = $parent_args['include'];
@@ -396,8 +515,12 @@
396 515 'answered_link_text' => array(
397 516 'description' => __( 'Text for the link to answers for the prompt.', 'jetpack' ),
398 517 'type' => 'string',
399 518 ),
519 + 'bloganuary_id' => array(
520 + 'description' => __( 'Id used by the bloganuary promotion', 'jetpack' ),
521 + 'type' => 'string',
522 + ),
400 523 ),
401 524 );
402 525 }
403 526
@@ -427,41 +550,8 @@
427 550 'rest_cannot_read_prompts',
428 551 __( 'Sorry, you are not allowed to access blogging prompts on this site.', 'jetpack' ),
429 552 array( 'status' => rest_authorization_required_code() )
430 553 );
431 - }
432 -
433 - /**
434 - * Proxy request to wpcom servers for the site and user.
435 - *
436 - * @param WP_Rest_Request $request Request to proxy.
437 - * @param string $path Path to append to the rest base.
438 - * @return mixed|WP_Error Response from wpcom servers or an error.
439 - */
440 - public function proxy_request_to_wpcom( $request, $path = '' ) {
441 - $blog_id = \Jetpack_Options::get_option( 'id' );
442 - $path = '/sites/' . rawurldecode( $blog_id ) . '/' . rawurldecode( $this->rest_base ) . ( $path ? '/' . rawurldecode( $path ) : '' );
443 - $api_url = add_query_arg( $request->get_query_params(), $path );
444 -
445 - // Prefer request as user, if possible. Fall back to blog request to show prompt data for unconnected users.
446 - $response = ( new Manager() )->is_user_connected()
447 - ? Client::wpcom_json_api_request_as_user( $api_url, '3', array(), null, 'wpcom' )
448 - : Client::wpcom_json_api_request_as_blog( $api_url, 'v3', array(), null, 'wpcom' );
449 -
450 - if ( is_wp_error( $response ) ) {
451 - return $response;
452 - }
453 -
454 - $response_status = wp_remote_retrieve_response_code( $response );
455 - $response_body = json_decode( wp_remote_retrieve_body( $response ) );
456 -
457 - if ( $response_status >= 400 ) {
458 - $code = isset( $response_body->code ) ? $response_body->code : 'unknown_error';
459 - $message = isset( $response_body->message ) ? $response_body->message : __( 'An unknown error occurred.', 'jetpack' );
460 - return new WP_Error( $code, $message, array( 'status' => $response_status ) );
461 - }
462 -
463 - return $response_body;
464 554 }
465 555
466 556 /**
467 557 * Creates a sample of users who have answered a blogging prompt.