Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
81.77% covered (warning)
81.77%
157 / 192
16.67% covered (danger)
16.67%
1 / 6
CRAP
0.00% covered (danger)
0.00%
0 / 1
WPCOM_JSON_API_Post_v1_1_Endpoint
82.63% covered (warning)
82.63%
157 / 190
16.67% covered (danger)
16.67%
1 / 6
108.06
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 get_post_by
72.73% covered (warning)
72.73%
16 / 22
0.00% covered (danger)
0.00%
0 / 1
12.03
 get_sal_post_by
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
2.03
 render_response_keys
99.25% covered (success)
99.25%
132 / 133
0.00% covered (danger)
0.00%
0 / 1
45
 filter_response
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
182
 get_blog_post
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3if ( ! defined( 'ABSPATH' ) ) {
4    exit( 0 );
5}
6
7/**
8 * Post v1_1 Endpoint class.
9 */
10abstract class WPCOM_JSON_API_Post_v1_1_Endpoint extends WPCOM_JSON_API_Endpoint { // phpcs:ignore PEAR.NamingConventions.ValidClassName.Invalid, Generic.Classes.OpeningBraceSameLine.ContentAfterBrace
11    /**
12     * Post object format.
13     *
14     * @var array
15     */
16    public $post_object_format = array(
17        // explicitly document and cast all output
18        'ID'               => '(int) The post ID.',
19        'site_ID'          => '(int) The site ID.',
20        'author'           => '(object>author) The author of the post.',
21        'date'             => "(ISO 8601 datetime) The post's creation time.",
22        'modified'         => "(ISO 8601 datetime) The post's most recent update time.",
23        'title'            => '(HTML) <code>context</code> dependent.',
24        'URL'              => '(URL) The full permalink URL to the post.',
25        'short_URL'        => '(URL) The wp.me short URL.',
26        'content'          => '(HTML) <code>context</code> dependent.',
27        'excerpt'          => '(HTML) <code>context</code> dependent.',
28        'slug'             => '(string) The name (slug) for the post, used in URLs.',
29        'guid'             => '(string) The GUID for the post.',
30        'status'           => array(
31            'publish'    => 'The post is published.',
32            'draft'      => 'The post is saved as a draft.',
33            'pending'    => 'The post is pending editorial approval.',
34            'private'    => 'The post is published privately',
35            'future'     => 'The post is scheduled for future publishing.',
36            'trash'      => 'The post is in the trash.',
37            'auto-draft' => 'The post is a placeholder for a new post.',
38        ),
39        'sticky'           => '(bool) Is the post sticky?',
40        'password'         => '(string) The plaintext password protecting the post, or, more likely, the empty string if the post is not password protected.',
41        'has_password'     => '(bool) Whether the post is password protected, regardless of whether the current user can access it.',
42        'parent'           => "(object>post_reference|false) A reference to the post's parent, if it has one.",
43        'type'             => "(string) The post's post_type. Post types besides post, page and revision need to be whitelisted using the <code>rest_api_allowed_post_types</code> filter.",
44        'discussion'       => '(object) Hash of discussion options for the post',
45        'likes_enabled'    => '(bool) Is the post open to likes?',
46        'sharing_enabled'  => '(bool) Should sharing buttons show on this post?',
47        'like_count'       => '(int) The number of likes for this post.',
48        'i_like'           => '(bool) Does the current user like this post?',
49        'is_reblogged'     => '(bool) Did the current user reblog this post?',
50        'is_following'     => '(bool) Is the current user following this blog?',
51        'global_ID'        => '(string) A unique WordPress.com-wide representation of a post.',
52        'featured_image'   => '(URL) The URL to the featured image for this post if it has one.',
53        'post_thumbnail'   => '(object>attachment) The attachment object for the featured image if it has one.',
54        'format'           => array(), // see constructor
55        'geo'              => '(object>geo|false)',
56        'menu_order'       => '(int) (Pages Only) The order pages should appear in.',
57        'page_template'    => '(string) (Pages Only) The page template this page is using.',
58        'publicize_URLs'   => '(array:URL) Array of Facebook URLs published by this post.',
59        'terms'            => '(object) Hash of taxonomy names mapping to a hash of terms keyed by term name.',
60        'tags'             => '(object:tag) Hash of tags (keyed by tag name) applied to the post.',
61        'categories'       => '(object:category) Hash of categories (keyed by category name) applied to the post.',
62        'attachments'      => '(object:attachment) Hash of post attachments (keyed by attachment ID). Returns the most recent 20 attachments. Use the `/sites/$site/media` endpoint to query the attachments beyond the default of 20 that are returned here.',
63        'attachment_count' => '(int) The total number of attachments for this post. Use the `/sites/$site/media` endpoint to query the attachments beyond the default of 20 that are returned here.',
64        'metadata'         => '(array) Array of post metadata keys and values. Users who can edit the post get its unprotected meta keys. Protected meta keys (those starting with an underscore) are returned only when the user can edit that key, which requires an <code>auth_callback</code> registered with <code>register_meta()</code> or an <code>auth_post_meta_{$meta_key}</code> filter. Keys allowed by the <code>rest_api_allowed_public_metadata</code> filter, plus <code>_thumbnail_id</code> and keys starting with <code>geo_</code> or <code>_wpas_</code>, are returned to anyone who can read the post. Most keys starting with <code>_jetpack_</code>, and all keys starting with <code>_elasticsearch_</code>, are never returned.',
65        'meta'             => '(object) API result meta data',
66        'capabilities'     => '(object) List of post-specific permissions for the user; publish_post, edit_post, delete_post',
67        'revisions'        => '(array) List of post revision IDs. Only available for posts retrieved with context=edit.',
68        'other_URLs'       => '(object) List of URLs for this post. Permalink and slug suggestions.',
69    );
70
71    /**
72     * Constructor function.
73     *
74     * @param string|array|object $args — Args.
75     */
76    public function __construct( $args ) {
77        if ( is_array( $this->post_object_format ) && isset( $this->post_object_format['format'] ) ) {
78            $this->post_object_format['format'] = get_post_format_strings();
79        }
80        if ( ! $this->response_format ) {
81            $this->response_format =& $this->post_object_format;
82        }
83        parent::__construct( $args );
84    }
85
86    /**
87     * Get a post by a specified field and value
88     *
89     * @param string $field - the field.
90     * @param string $field_value - the field value.
91     * @param string $context Post use context (e.g. 'display').
92     *
93     * @return array|WP_Error Post
94     **/
95    public function get_post_by( $field, $field_value, $context = 'display' ) {
96
97        // validate input
98        if ( ! in_array( $field, array( 'ID', 'name' ), true ) ) {
99            return new WP_Error( 'invalid_field', 'Invalid API FIELD', 400 );
100        }
101
102        if ( ! in_array( $context, array( 'display', 'edit' ), true ) ) {
103            return new WP_Error( 'invalid_context', 'Invalid API CONTEXT', 400 );
104        }
105
106        if ( 'display' === $context ) {
107            $args = $this->query_args();
108            if ( isset( $args['content_width'] ) && $args['content_width'] ) {
109                $GLOBALS['content_width'] = (int) $args['content_width'];
110            }
111        }
112
113        // fetch SAL post
114        $post = $this->get_sal_post_by( $field, $field_value, $context );
115
116        if ( is_wp_error( $post ) ) {
117            return $post;
118        }
119
120        $GLOBALS['post'] = $post->post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
121
122        // TODO: not sure where this one should go
123        if ( 'display' === $context ) {
124            setup_postdata( $post->post );
125        }
126
127        $keys_to_render = array_keys( $this->post_object_format );
128        // See WPCOM_JSON_API::filter_fields().
129        if ( isset( $this->api->query['fields'] ) && is_string( $this->api->query['fields'] ) ) {
130            $limit_to_fields = array_map( 'trim', explode( ',', $this->api->query['fields'] ) );
131            $keys_to_render  = array_intersect( $keys_to_render, $limit_to_fields );
132        }
133
134        // always include some keys because processors require it to validate access
135        $keys_to_render = array_unique( array_merge( $keys_to_render, array( 'type', 'status', 'password' ) ) );
136
137        $response = $this->render_response_keys( $post, $context, $keys_to_render );
138
139        unset( $GLOBALS['post'] );
140
141        return $response;
142    }
143
144    /**
145     * Get SAL post by a specified field and value
146     *
147     * @param string $field - the field.
148     * @param string $field_value - the field value.
149     * @param string $context Post use context (e.g. 'display').
150     *
151     * @return SAL_Post|WP_Error Post
152     **/
153    protected function get_sal_post_by( $field, $field_value, $context ) {
154        global $blog_id;
155
156        $site = $this->get_platform()->get_site( $blog_id );
157
158        $post = ( $field === 'name' ) ?
159            $site->get_post_by_name( $field_value, $context ) :
160            $site->get_post_by_id( $field_value, $context );
161
162        return $post;
163    }
164
165    /**
166     * Render the response keys.
167     *
168     * @param object $post - the post.
169     * @param string $context Post use context (e.g. 'display').
170     * @param array  $keys - the keys.
171     *
172     * @return array
173     */
174    private function render_response_keys( $post, $context, $keys ) {
175        $response = array();
176        foreach ( $keys as $key ) {
177            switch ( $key ) {
178                case 'ID':
179                    // explicitly cast all output
180                    $response[ $key ] = (int) $post->ID;
181                    break;
182                case 'site_ID':
183                    $response[ $key ] = $post->site->get_id();
184                    break;
185                case 'author':
186                    $response[ $key ] = $post->get_author();
187                    break;
188                case 'date':
189                    $response[ $key ] = $post->get_date();
190                    break;
191                case 'modified':
192                    $response[ $key ] = $post->get_modified_date();
193                    break;
194                case 'title':
195                    $response[ $key ] = $post->get_title();
196                    break;
197                case 'URL':
198                    $response[ $key ] = $post->get_url();
199                    break;
200                case 'short_URL':
201                    $response[ $key ] = $post->get_shortlink();
202                    break;
203                case 'content':
204                    $response[ $key ] = $post->get_content();
205                    break;
206                case 'excerpt':
207                    $response[ $key ] = $post->get_excerpt();
208                    break;
209                case 'status':
210                    $response[ $key ] = $post->get_status();
211                    break;
212                case 'sticky':
213                    $response[ $key ] = $post->is_sticky();
214                    break;
215                case 'slug':
216                    $response[ $key ] = $post->get_slug();
217                    break;
218                case 'guid':
219                    $response[ $key ] = $post->get_guid();
220                    break;
221                case 'password':
222                    $response[ $key ] = $post->get_password();
223                    break;
224                case 'has_password':
225                    $response[ $key ] = $post->get_has_password();
226                    break;
227                /** (object|false) */
228                case 'parent':
229                    $response[ $key ] = $post->get_parent();
230                    break;
231                case 'type':
232                    $response[ $key ] = $post->get_type();
233                    break;
234                case 'discussion':
235                    $response[ $key ] = $post->get_discussion();
236                    break;
237                case 'likes_enabled':
238                    $response[ $key ] = $post->is_likes_enabled();
239                    break;
240                case 'sharing_enabled':
241                    $response[ $key ] = $post->is_sharing_enabled();
242                    break;
243                case 'like_count':
244                    $response[ $key ] = $post->get_like_count();
245                    break;
246                case 'i_like':
247                    $response[ $key ] = $post->is_liked();
248                    break;
249                case 'is_reblogged':
250                    $response[ $key ] = $post->is_reblogged();
251                    break;
252                case 'is_following':
253                    $response[ $key ] = $post->is_following();
254                    break;
255                case 'global_ID':
256                    $response[ $key ] = $post->get_global_id();
257                    break;
258                case 'featured_image':
259                    $response[ $key ] = $post->get_featured_image();
260                    break;
261                case 'post_thumbnail':
262                    $response[ $key ] = $post->get_post_thumbnail();
263                    break;
264                case 'format':
265                    $response[ $key ] = $post->get_format();
266                    break;
267                /** (object|false) */
268                case 'geo':
269                    $response[ $key ] = $post->get_geo();
270                    break;
271                case 'menu_order':
272                    $response[ $key ] = $post->get_menu_order();
273                    break;
274                case 'page_template':
275                    $response[ $key ] = $post->get_page_template();
276                    break;
277                case 'publicize_URLs':
278                    $response[ $key ] = $post->get_publicize_urls();
279                    break;
280                case 'terms':
281                    $response[ $key ] = $post->get_terms();
282                    break;
283                case 'tags':
284                    $response[ $key ] = $post->get_tags();
285                    break;
286                case 'categories':
287                    $response[ $key ] = $post->get_categories();
288                    break;
289                case 'attachments':
290                    list( $attachments, $attachment_count ) = $post->get_attachments_and_count();
291                    $response[ $key ]                       = $attachments;
292                    $response['attachment_count']           = $attachment_count;
293                    break;
294                /** (array|false) */
295                case 'metadata':
296                    $response[ $key ] = $post->get_metadata();
297                    break;
298                case 'meta':
299                    $response[ $key ] = $post->get_meta();
300                    break;
301                case 'capabilities':
302                    $response[ $key ] = $post->get_current_user_capabilities();
303                    break;
304                case 'revisions':
305                    $revisions = $post->get_revisions();
306                    if ( $revisions ) {
307                        $response[ $key ] = $revisions;
308                    }
309                    break;
310                case 'other_URLs':
311                    $response[ $key ] = $post->get_other_urls();
312                    break;
313            }
314        }
315
316        return $response;
317    }
318
319    /**
320     * Filter respnse.
321     *
322     * @param array $response - the response.
323     * @return array Filtered response.
324     */
325    public function filter_response( $response ) {
326
327        // Do minimal processing if the caller didn't request it
328        if ( ! isset( $_REQUEST['meta_fields'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- we're not making any changes to the site.
329            return $response;
330        }
331
332        // Bail early if we do not have the necessary data.
333        if (
334            is_wp_error( $response )
335            || ! isset( $response['posts'] )
336            || ! is_array( $response['posts'] )
337        ) {
338            return $response;
339        }
340
341        // Retrieve an array of field paths, such as: [`autosave.modified`, `autosave.post_ID`]
342        $fields = explode( ',', sanitize_text_field( wp_unslash( $_REQUEST['meta_fields'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- we're not making any changes to the site.
343
344        foreach ( $response['posts'] as $post ) {
345
346            if ( ! isset( $post['meta'] ) || ! isset( $post['meta']->data ) || ( ! is_array( $post['meta']->data ) && ! is_object( $post['meta']->data ) ) ) {
347                continue;
348            }
349
350            $newmeta = array();
351            foreach ( $post['meta']->data as $field_key => $field_value ) {
352
353                foreach ( $field_value as $subfield_key => $subfield_value ) {
354                    $key_path = $field_key . '.' . $subfield_key;
355
356                    if ( in_array( $key_path, $fields, true ) ) {
357                        $newmeta[ $field_key ][ $subfield_key ] = $subfield_value;
358                    }
359                }
360            }
361
362            $post['meta']->data = $newmeta;
363        }
364
365        return $response;
366    }
367
368    /**
369     * Gets the blog post.
370     *
371     * @param int    $blog_id - the blog ID.
372     * @param int    $post_id - the post ID.
373     * @param string $context - the context.
374     *
375     * @return array|bool|WP_Error
376     */
377    public function get_blog_post( $blog_id, $post_id, $context = 'display' ) {
378        $blog_id = $this->api->get_blog_id( $blog_id );
379        if ( ! $blog_id || is_wp_error( $blog_id ) ) {
380            return $blog_id;
381        }
382        switch_to_blog( $blog_id );
383        $post = $this->get_post_by( 'ID', $post_id, $context );
384        restore_current_blog();
385        return $post;
386    }
387}