Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
1.28% covered (danger)
1.28%
5 / 392
6.12% covered (danger)
6.12%
3 / 49
CRAP
0.00% covered (danger)
0.00%
0 / 1
SAL_Post
1.30% covered (danger)
1.30%
5 / 386
6.12% covered (danger)
6.12%
3 / 49
23558.50
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 __set
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 __get
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 __call
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 __isset
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_like_count
n/a
0 / 0
n/a
0 / 0
0
 is_liked
n/a
0 / 0
n/a
0 / 0
0
 is_reblogged
n/a
0 / 0
n/a
0 / 0
0
 is_following
n/a
0 / 0
n/a
0 / 0
0
 get_global_id
n/a
0 / 0
n/a
0 / 0
0
 get_geo
n/a
0 / 0
n/a
0 / 0
0
 get_menu_order
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_guid
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_type
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_terms
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
30
 get_tags
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 get_categories
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
12
 get_attachments_and_count
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 get_metadata
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
56
 get_meta
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
30
 get_current_user_capabilities
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 get_revisions
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 get_other_urls
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get_site_link
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_post_link
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_publicize_urls
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
240
 get_page_template
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_featured_image
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 get_post_thumbnail
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 get_format
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get_attachment
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
 get_date
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_modified_date
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_title
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_url
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_shortlink
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_content
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_excerpt
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 get_status
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 is_sticky
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_slug
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_password
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get_has_password
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_parent
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 the_password_form
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_discussion
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 is_likes_enabled
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
 is_sharing_enabled
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 get_the_post_content_for_display
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
2
 get_author
0.00% covered (danger)
0.00%
0 / 27
0.00% covered (danger)
0.00%
0 / 1
90
 get_avatar_url
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
 get_permalink_suggestions
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 format_taxonomy
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
72
 get_media_item_v1_1
0.00% covered (danger)
0.00%
0 / 80
0.00% covered (danger)
0.00%
0 / 1
1056
 safe_maybe_unserialize
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
1<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2/**
3 * This class wraps a WP_Post and proxies any undefined attributes
4 * and methods to the wrapped class. We need to do this because at present
5 * the WP_Post class is marked as final (in 4.5 this will change, though it's
6 * not clear if there will be a mechanism to retrieve from the DB into the over-
7 * ridden class dynamically).
8 *
9 * @package automattic/jetpack
10 */
11
12use Automattic\Jetpack\Status;
13
14if ( ! defined( 'ABSPATH' ) ) {
15    exit( 0 );
16}
17
18require_once __DIR__ . '/class.json-api-metadata.php';
19require_once __DIR__ . '/class.json-api-date.php';
20require_once ABSPATH . 'wp-admin/includes/post.php';
21require_once ABSPATH . 'wp-includes/post.php';
22
23/**
24 * Base class for SAL_Post.
25 */
26abstract class SAL_Post {
27
28    /**
29     * A WP_Post instance.
30     *
31     * @var WP_Post
32     */
33    public $post;
34
35    /**
36     * The post request context (for example 'edit' or 'display')
37     *
38     * @var string
39     */
40    public $context;
41
42    /**
43     * A Jetpack_Site instance.
44     *
45     * @var Jetpack_Site
46     */
47    public $site;
48
49    /**
50     * Constructor function
51     *
52     * @param Jetpack_Site $site A Jetpack_Site instance.
53     * @param WP_Post      $post A WP_Post instance.
54     * @param string       $context The post request context (for example 'edit' or 'display').
55     */
56    public function __construct( $site, $post, $context ) {
57        $this->post    = $post;
58        $this->context = $context;
59        $this->site    = $site;
60    }
61
62    /**
63     * Setting this WP_Post instance's key value
64     *
65     * @param string $key The post key to set.
66     * @param string $value The value to set the post key to (for example filter, ID, post_status).
67     */
68    public function __set( $key, $value ) {
69        $this->post->{ $key } = $value;
70    }
71
72    /**
73     * Returning a WPCOM_JSON_API_Links instance if the post key is set to 'links', or the post key value.
74     *
75     * @param string $key The post key value.
76     *
77     * @return WPCOM_JSON_API_Links|string
78     */
79    public function __get( $key ) {
80        if ( 'links' === $key ) {
81            require_once __DIR__ . '/class.json-api-links.php';
82            return WPCOM_JSON_API_Links::getInstance();
83        }
84        return $this->post->{ $key };
85    }
86
87    /**
88     * A function to either call a given function, or return an error if it doesn't exist.
89     *
90     * @param string $name A function name to be called.
91     * @param mixed  $arguments Arguments to be passed into the given function.
92     *
93     * @return mixed|bool
94     */
95    public function __call( $name, $arguments ) {
96        if ( is_callable( array( $this->post, $name ) ) ) {
97            return call_user_func_array( array( $this->post, $name ), $arguments );
98        } else {
99            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
100            trigger_error(
101                esc_html(
102                    sprintf(
103                        /* translators: %s is the method name that has been called */
104                        __( 'Call to undefined method %s', 'jetpack' ),
105                        $name
106                    )
107                )
108            );
109        }
110    }
111
112    /**
113     * Checking to see if a given property is set.
114     *
115     * @param string $name Property to check if set.
116     *
117     * @return bool
118     */
119    public function __isset( $name ) {
120        return isset( $this->post->{ $name } );
121    }
122
123    /**
124     * Defining a base get_like_count() function to be extended in the Jetpack_Post class.
125     *
126     * This will define a default value for the like counts on a post, if this hasn't been defined yet.
127     *
128     * @see class.json-api-post-jetpack.php
129     */
130    abstract public function get_like_count();
131
132    /**
133     * Defining a base is_liked() function to be extended in the Jetpack_Post class.
134     *
135     * This will define a default value for whether or not the current user likes this post, if this hasn't been defined yet.
136     *
137     * @see class.json-api-post-jetpack.php
138     */
139    abstract public function is_liked();
140
141    /**
142     * Defining a base is_reblogged() function to be extended in the Jetpack_Post class.
143     *
144     * This will define a default value for whether or not the current user reblogged this post, if this hasn't been defined yet.
145     *
146     * @see class.json-api-post-jetpack.php
147     */
148    abstract public function is_reblogged();
149
150    /**
151     * Defining a base is_following() function to be extended in the Jetpack_Post class.
152     *
153     * This will define a default value for whether or not the current user is following this blog, if this hasn't been defined yet.
154     *
155     * @see class.json-api-post-jetpack.php
156     */
157    abstract public function is_following();
158
159    /**
160     * Defining a base get_global_id() function to be extended in the Jetpack_Post class.
161     *
162     * This will define the unique WordPress.com-wide representation of a post, if this hasn't been defined yet.
163     *
164     * @see class.json-api-post-jetpack.php
165     */
166    abstract public function get_global_id();
167
168    /**
169     * Defining a base get_geo() function to be extended in the Jetpack_Post class.
170     *
171     * This will define a default value for whether or not there is gelocation data for this post, if this hasn't been defined yet.
172     *
173     * @see class.json-api-post-jetpack.php
174     */
175    abstract public function get_geo();
176
177    /**
178     * Returns an int which helps define the menu order for the post.
179     *
180     * @return int
181     */
182    public function get_menu_order() {
183        return (int) $this->post->menu_order;
184    }
185
186    /**
187     * Returns a string which represents the post's GUID.
188     *
189     * @return string
190     */
191    public function get_guid() {
192        return (string) $this->post->guid;
193    }
194
195    /**
196     * Returns a string which represents the post type.
197     *
198     * @return string
199     */
200    public function get_type() {
201        return (string) $this->post->post_type;
202    }
203
204    /**
205     * Returns an object which holds the terms associated with that post object.
206     *
207     * @return object
208     */
209    public function get_terms() {
210        $taxonomies = get_object_taxonomies( $this->post, 'objects' );
211        $terms      = array();
212        foreach ( $taxonomies as $taxonomy ) {
213            if ( ! $taxonomy->public && ! current_user_can( $taxonomy->cap->assign_terms ) ) {
214                continue;
215            }
216
217            $terms[ $taxonomy->name ] = array();
218
219            $taxonomy_terms = wp_get_object_terms( $this->post->ID, $taxonomy->name, array( 'fields' => 'all' ) );
220            foreach ( $taxonomy_terms as $term ) {
221                $formatted_term                          = $this->format_taxonomy( $term, $taxonomy->name, 'display' );
222                $terms[ $taxonomy->name ][ $term->name ] = $formatted_term;
223            }
224
225            $terms[ $taxonomy->name ] = (object) $terms[ $taxonomy->name ];
226        }
227
228        return (object) $terms;
229    }
230
231    /**
232     * Returns an object which holds the posts tag details
233     *
234     * @return object
235     */
236    public function get_tags() {
237        $tags  = array();
238        $terms = wp_get_post_tags( $this->post->ID );
239        foreach ( $terms as $term ) {
240            if ( ! empty( $term->name ) ) {
241                $tags[ $term->name ] = $this->format_taxonomy( $term, 'post_tag', 'display' );
242            }
243        }
244        return (object) $tags;
245    }
246
247    /**
248     * Returns an object which holds the posts category details
249     *
250     * @return object
251     */
252    public function get_categories() {
253        $categories = array();
254        $terms      = wp_get_object_terms( $this->post->ID, 'category', array( 'fields' => 'all' ) );
255        foreach ( $terms as $term ) {
256            if ( ! empty( $term->name ) ) {
257                $categories[ $term->name ] = $this->format_taxonomy( $term, 'category', 'display' );
258            }
259        }
260        return (object) $categories;
261    }
262
263    /**
264     * Returns an array of objects which hold the posts attachment information and numbers representing how many associated posts are found.
265     *
266     * @return array
267     */
268    public function get_attachments_and_count() {
269        $attachments  = array();
270        $_attachments = new WP_Query(
271            array(
272                'post_parent'    => $this->post->ID,
273                'post_status'    => 'inherit',
274                'post_type'      => 'attachment',
275                'posts_per_page' => '20',
276            )
277        );
278        foreach ( $_attachments->posts as $attachment ) {
279            $attachments[ $attachment->ID ] = $this->get_media_item_v1_1( $attachment->ID );
280        }
281        return array( (object) $attachments, (int) $_attachments->found_posts );
282    }
283
284    /**
285     * Returns an array with a posts metadata information.
286     *
287     * @return array
288     */
289    public function get_metadata() {
290        $metadata = array();
291        foreach ( (array) has_meta( $this->post->ID ) as $meta ) {
292            // Don't expose protected fields.
293            $meta_key = $meta['meta_key'];
294
295            $show = ! ( WPCOM_JSON_API_Metadata::is_internal_only( $meta_key ) )
296                &&
297                    (
298                        WPCOM_JSON_API_Metadata::is_public( $meta_key )
299                    ||
300                        current_user_can( 'edit_post_meta', $this->post->ID, $meta_key )
301                    );
302
303            if ( Jetpack_SEO_Posts::DESCRIPTION_META_KEY === $meta_key && ! Jetpack_SEO_Utils::is_enabled_jetpack_seo() ) {
304                $show = false;
305            }
306
307            if ( $show ) {
308                $metadata[] = array(
309                    'id'    => $meta['meta_id'],
310                    'key'   => $meta['meta_key'],
311                    'value' => $this->safe_maybe_unserialize( $meta['meta_value'] ),
312                );
313            }
314        }
315
316        return $metadata;
317    }
318
319    /**
320     * Returns an object with a posts link meta details.
321     *
322     * @return object
323     */
324    public function get_meta() {
325        $meta = (object) array(
326            'links' => (object) array(
327                'self'    => (string) $this->get_post_link(),
328                'help'    => (string) $this->get_post_link( 'help' ),
329                'site'    => (string) $this->get_site_link(),
330                'replies' => (string) $this->get_post_link( 'replies/' ),
331                'likes'   => (string) $this->get_post_link( 'likes/' ),
332            ),
333        );
334
335        $amp_permalink = get_post_meta( $this->post->ID, '_jetpack_amp_permalink', true );
336
337        if ( ! empty( $amp_permalink ) ) {
338            $meta->links->amp = (string) $amp_permalink;
339        }
340
341        // add autosave link if a more recent autosave exists.
342        if ( 'edit' === $this->context ) {
343            $autosave = wp_get_post_autosave( $this->post->ID );
344            if ( $autosave && $autosave->post_modified > $this->post->post_modified ) {
345                $meta->links->autosave = (string) $this->get_post_link() . '/autosave';
346            }
347        }
348
349        return $meta;
350    }
351
352    /**
353     * Returns an array with the current user's publish, deletion and edit capabilities.
354     *
355     * @return array
356     */
357    public function get_current_user_capabilities() {
358        return array(
359            'publish_post' => current_user_can( 'publish_post', $this->post->ID ),
360            'delete_post'  => current_user_can( 'delete_post', $this->post->ID ),
361            'edit_post'    => current_user_can( 'edit_post', $this->post->ID ),
362        );
363    }
364
365    /**
366     * Returns an array with post revision ids, or false if 'edit' isn't the current post request context.
367     *
368     * @return bool|array
369     */
370    public function get_revisions() {
371        if ( 'edit' !== $this->context ) {
372            return false;
373        }
374
375        $args = array(
376            'posts_per_page' => -1,
377            'post_type'      => 'revision',
378            'post_status'    => 'any',
379            'fields'         => 'ids',  // Fetch only the IDs.
380            'post_parent'    => $this->post->ID,
381        );
382
383        $revision_query = new WP_Query( $args );
384        return $revision_query->posts;  // This returns an array of revision IDs.
385    }
386
387    /**
388     * Returns an object with extra post permalink suggestions.
389     *
390     * @return object
391     */
392    public function get_other_urls() {
393        $other_urls = array();
394
395        if ( 'publish' !== $this->post->post_status ) {
396            $other_urls = $this->get_permalink_suggestions( $this->post->post_title );
397        }
398
399        return (object) $other_urls;
400    }
401
402    /**
403     * Calls the WPCOM_JSON_API_Links get_site_link() function to generate a site link endpoint URL.
404     *
405     * @return string Endpoint URL including site information.
406     */
407    protected function get_site_link() {
408        return $this->links->get_site_link( $this->site->get_id() );
409    }
410
411    /**
412     * Calls the WPCOM_JSON_API_Links get_post_link() function to generate a posts endpoint URL.
413     *
414     * @param string $path  Optional path to be appended to the URL.
415     * @return string Endpoint URL including post information.
416     */
417    protected function get_post_link( $path = null ) {
418        return $this->links->get_post_link( $this->site->get_id(), $this->post->ID, $path );
419    }
420
421    /**
422     * Returns an array of user and post specific social media post URLs.
423     *
424     * @return array
425     */
426    public function get_publicize_urls() {
427        $publicize_urls = array();
428        $publicize      = get_post_meta( $this->post->ID, 'publicize_results', true );
429        if ( $publicize ) {
430            // get_post_meta(..., true) will return a string if the value was stored as a scalar or serialized, so we may need to unserialize.
431            if ( is_string( $publicize ) ) {
432                $maybe_array_publicize = maybe_unserialize( $publicize );
433                if ( ! is_array( $maybe_array_publicize ) ) {
434                    $maybe_array_publicize = json_decode( $publicize, true );
435                }
436                if ( is_array( $maybe_array_publicize ) ) {
437                    $publicize = $maybe_array_publicize;
438                } else {
439                    return $publicize_urls;
440                }
441            }
442
443            if ( is_array( $publicize ) ) {
444                foreach ( $publicize as $service => $data ) {
445                    switch ( $service ) {
446                        // @todo explore removing once Twitter is removed from Publicize.
447                        case 'twitter':
448                            foreach ( $data as $datum ) {
449                                if ( isset( $datum['user_id'] ) && isset( $datum['post_id'] ) ) {
450                                    $publicize_urls[] = esc_url_raw( "https://twitter.com/{$datum['user_id']}/status/{$datum['post_id']}" );
451                                }
452                            }
453                            break;
454                        case 'fb':
455                            foreach ( $data as $datum ) {
456                                if ( isset( $datum['user_id'] ) && isset( $datum['post_id'] ) ) {
457                                    $publicize_urls[] = esc_url_raw( "https://www.facebook.com/permalink.php?story_fbid={$datum['post_id']}&id={$datum['user_id']}" );
458                                }
459                            }
460                            break;
461                    }
462                }
463            }
464        }
465        return $publicize_urls;
466    }
467
468    /**
469     * Returns a string with the page's custom template metadata.
470     *
471     * @return string
472     */
473    public function get_page_template() {
474        return (string) get_post_meta( $this->post->ID, '_wp_page_template', true );
475    }
476
477    /**
478     * Returns a string representing the source URL of a post's featured image (or an empty string otherwise).
479     *
480     * Note - this is overridden in jetpack-shadow
481     *
482     * @return string
483     */
484    public function get_featured_image() {
485        $image_attributes = wp_get_attachment_image_src( get_post_thumbnail_id( $this->post->ID ), 'full' );
486        if ( is_array( $image_attributes ) && isset( $image_attributes[0] ) ) {
487            return (string) $image_attributes[0];
488        } else {
489            return '';
490        }
491    }
492
493    /**
494     * Returns an object representing a post's featured image thumbnail image.
495     *
496     * @return object
497     */
498    public function get_post_thumbnail() {
499        $thumb = null;
500
501        $thumb_id = get_post_thumbnail_id( $this->post->ID );
502
503        if ( ! empty( $thumb_id ) ) {
504            $attachment = get_post( $thumb_id );
505            if ( ! empty( $attachment ) ) {
506                $featured_image_object = $this->get_attachment( $attachment );
507            }
508            if ( ! empty( $featured_image_object ) ) {
509                $thumb = (object) $featured_image_object;
510            }
511        }
512
513        return $thumb;
514    }
515
516    /**
517     * Returns the format slug for a post (for example 'link', 'image' - the default being 'standard').
518     *
519     * @return string
520     */
521    public function get_format() {
522        $format = (string) get_post_format( $this->post->ID );
523        if ( ! $format ) {
524            $format = 'standard';
525        }
526
527        return $format;
528    }
529
530    /**
531     * Returns an object with the post's attachment details.
532     *
533     * @param WP_POST $attachment The post's attachment details in the form of a WP_POST object.
534     *
535     * @return object
536     */
537    private function get_attachment( $attachment ) {
538        $metadata = wp_get_attachment_metadata( $attachment->ID );
539
540        $result = array(
541            'ID'        => (int) $attachment->ID,
542            'URL'       => (string) wp_get_attachment_url( $attachment->ID ),
543            'guid'      => (string) $attachment->guid,
544            'mime_type' => (string) $attachment->post_mime_type,
545            'width'     => (int) isset( $metadata['width'] ) ? $metadata['width'] : 0,
546            'height'    => (int) isset( $metadata['height'] ) ? $metadata['height'] : 0,
547        );
548
549        if ( isset( $metadata['duration'] ) ) {
550            $result['duration'] = (int) $metadata['duration'];
551        }
552
553        /** This filter is documented in class.jetpack-sync.php */
554        return (object) apply_filters( 'get_attachment', $result );
555    }
556
557    /**
558     * Returns an ISO 8601 formatted datetime string representing the date of post creation.
559     *
560     * @return string
561     */
562    public function get_date() {
563        return (string) WPCOM_JSON_API_Date::format_date( $this->post->post_date_gmt, $this->post->post_date );
564    }
565
566    /**
567     * Returns an ISO 8601 formatted datetime string representing the date the post was last modified.
568     *
569     * @return string
570     */
571    public function get_modified_date() {
572        return (string) WPCOM_JSON_API_Date::format_date( $this->post->post_modified_gmt, $this->post->post_modified );
573    }
574
575    /**
576     * Returns the post's title.
577     *
578     * @return string
579     */
580    public function get_title() {
581        if ( 'display' === $this->context ) {
582            return (string) get_the_title( $this->post->ID );
583        } else {
584            return htmlspecialchars_decode( $this->post->post_title, ENT_QUOTES );
585        }
586    }
587
588    /**
589     * Returns the permalink for the post (or the post parent if the post type is a revision).
590     *
591     * @return string
592     */
593    public function get_url() {
594        if ( 'revision' === $this->post->post_type ) {
595            return (string) esc_url_raw( get_permalink( $this->post->post_parent ) );
596        } else {
597            return (string) esc_url_raw( get_permalink( $this->post->ID ) );
598        }
599    }
600
601    /**
602     * Returns the shortlink for the post.
603     *
604     * @return string
605     */
606    public function get_shortlink() {
607        return (string) esc_url_raw( wp_get_shortlink( $this->post->ID ) );
608    }
609
610    /**
611     * Returns the post content, or a string saying 'This post is password protected' if that is the case.
612     *
613     * @return string
614     */
615    public function get_content() {
616        if ( 'display' === $this->context ) {
617            // @todo: move this WPCOM-specific hack
618            add_filter( 'the_password_form', array( $this, 'the_password_form' ) );
619            $content = (string) $this->get_the_post_content_for_display();
620            remove_filter( 'the_password_form', array( $this, 'the_password_form' ) );
621            return $content;
622        } else {
623            return (string) $this->post->post_content;
624        }
625    }
626
627    /**
628     * Returns the post excerpt, or a string saying 'This post is password protected' if that is the case.
629     *
630     * @return string
631     */
632    public function get_excerpt() {
633        if ( 'display' === $this->context ) {
634            add_filter( 'the_password_form', array( $this, 'the_password_form' ) );
635            ob_start();
636            the_excerpt();
637            $response = (string) ob_get_clean();
638            remove_filter( 'the_password_form', array( $this, 'the_password_form' ) );
639        } else {
640            $response = htmlspecialchars_decode( (string) $this->post->post_excerpt, ENT_QUOTES );
641        }
642        return $response;
643    }
644
645    /**
646     * Returns the current post status (publish, future, draft, pending, private).
647     *
648     * @return string
649     */
650    public function get_status() {
651        return (string) get_post_status( $this->post->ID );
652    }
653
654    /**
655     * Returns true if the post is a sticky post, false otherwise.
656     *
657     * @return bool
658     */
659    public function is_sticky() {
660        return (bool) is_sticky( $this->post->ID );
661    }
662
663    /**
664     * Returns the post's slug.
665     *
666     * @return string
667     */
668    public function get_slug() {
669        return (string) $this->post->post_name;
670    }
671
672    /**
673     * Returns the post's password, if password protected.
674     *
675     * @return string
676     */
677    public function get_password() {
678        $password = (string) $this->post->post_password;
679        if ( 'edit' === $this->context ) {
680            $password = htmlspecialchars_decode( $password, ENT_QUOTES );
681        }
682        return $password;
683    }
684
685    /**
686     * Returns true if the post has a password set, regardless of whether the current user can view or receive the password value.
687     *
688     * @return bool
689     */
690    public function get_has_password(): bool {
691        return strlen( (string) $this->post->post_password ) > 0;
692    }
693
694    /**
695     * Returns an object representing a post's parent, and false if it doesn't have one.
696     *
697     * @return object|bool
698     */
699    public function get_parent() {
700        if ( $this->post->post_parent ) {
701            $parent = get_post( $this->post->post_parent );
702            if ( ! $parent ) {
703                return false;
704            }
705            if ( 'display' === $this->context ) {
706                $parent_title = (string) get_the_title( $parent->ID );
707            } else {
708                $parent_title = htmlspecialchars_decode( $this->post->post_title, ENT_QUOTES );
709            }
710            return (object) array(
711                'ID'    => (int) $parent->ID,
712                'type'  => (string) $parent->post_type,
713                'link'  => (string) $this->links->get_post_link( $this->site->get_id(), $parent->ID ),
714                'title' => $parent_title,
715            );
716        } else {
717            return false;
718        }
719    }
720
721    /**
722     * Returns a string saying 'This post is password protected' (to be later used within the_password_form filter).
723     *
724     * @return string
725     */
726    public function the_password_form() {
727        return __( 'This post is password protected.', 'jetpack' );
728    }
729
730    /**
731     * Returns an array with information related to the comment and ping status of a post.
732     *
733     * @return array
734     */
735    public function get_discussion() {
736        return array(
737            'comments_open'  => (bool) comments_open( $this->post->ID ),
738            'comment_status' => (string) $this->post->comment_status,
739            'pings_open'     => (bool) pings_open( $this->post->ID ),
740            'ping_status'    => (string) $this->post->ping_status,
741            'comment_count'  => (int) $this->post->comment_count,
742        );
743    }
744
745    /**
746     * Returns true if likes are enabled - either for the post, or site-wide.
747     *
748     * @return bool
749     */
750    public function is_likes_enabled() {
751        /** This filter is documented in modules/likes.php */
752        $sitewide_likes_enabled = (bool) apply_filters( 'wpl_is_enabled_sitewide', ! get_option( 'disabled_likes' ) );
753        $post_likes_switched    = get_post_meta( $this->post->ID, 'switch_like_status', true );
754
755        return $post_likes_switched || ( $sitewide_likes_enabled && '0' !== $post_likes_switched );
756    }
757
758    /**
759     * Returns true if sharing is enabled, false otherwise.
760     *
761     * @return bool
762     */
763    public function is_sharing_enabled() {
764        $show = true;
765        /** This filter is documented in modules/sharedaddy/sharing-service.php */
766        $show = apply_filters( 'sharing_show', $show, $this->post );
767
768        $switched_status = get_post_meta( $this->post->ID, 'sharing_disabled', false );
769
770        if ( ! empty( $switched_status ) ) {
771            $show = false;
772        }
773
774        return (bool) $show;
775    }
776
777    /**
778     * Returns the post content in the form of a string, ready for displaying.
779     *
780     * Note: No Blog ID parameter.  No Post ID parameter.  Depends on globals.
781     * Expects setup_postdata() to already have been run
782     *
783     * @return string
784     */
785    public function get_the_post_content_for_display() {
786        global $pages, $page;
787
788        $old_pages = $pages;
789        $old_page  = $page;
790
791        $content = implode( "\n\n", $pages );
792        $content = preg_replace( '/<!--more(.*?)?-->/', '', $content );
793        // phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited -- Assignment to globals is intentional
794        $pages = array( $content );
795        $page  = 1;
796
797        ob_start();
798        the_content();
799        $return = ob_get_clean();
800
801        $pages = $old_pages;
802        $page  = $old_page;
803        // phpcs:enable WordPress.WP.GlobalVariablesOverride.Prohibited
804        return $return;
805    }
806
807    /**
808     * Returns an object containing the post author's information (eg. ID, display name, email if the user has post editing capabilities).
809     *
810     * @return object
811     */
812    public function get_author() {
813        if ( 0 == $this->post->post_author ) { // phpcs:ignore Universal.Operators.StrictComparisons.LooseEqual -- numbers could be numeric strings.
814            return null;
815        }
816
817        $show_email = 'edit' === $this->context && current_user_can( 'edit_post', $this->post->ID );
818
819        $user = get_user_by( 'id', $this->post->post_author );
820
821        if ( ! $user || is_wp_error( $user ) ) {
822            return null;
823        }
824
825        // @todo: factor this out
826        // phpcs:disable WordPress.NamingConventions.ValidVariableName
827        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
828            $active_blog = get_active_blog_for_user( $user->ID );
829            $site_id     = $active_blog->blog_id ?? -1;
830            $profile_URL = "https://gravatar.com/{$user->user_login}";
831        } else {
832            $profile_URL = 'https://gravatar.com/' . md5( strtolower( trim( $user->user_email ) ) );
833            $site_id     = -1;
834        }
835
836        $author = array(
837            'ID'          => (int) $user->ID,
838            'login'       => (string) $user->user_login,
839            'email'       => $show_email ? (string) $user->user_email : false,
840            'name'        => (string) $user->display_name,
841            'first_name'  => (string) $user->first_name,
842            'last_name'   => (string) $user->last_name,
843            'nice_name'   => (string) $user->user_nicename,
844            'URL'         => (string) esc_url_raw( $user->user_url ),
845            'avatar_URL'  => (string) esc_url_raw( $this->get_avatar_url( $user->user_email ) ),
846            'profile_URL' => (string) esc_url_raw( $profile_URL ),
847        );
848        // phpcs:enable WordPress.NamingConventions.ValidVariableName
849
850        if ( $site_id > -1 ) {
851            $author['site_ID'] = (int) $site_id;
852        }
853
854        return (object) $author;
855    }
856
857    /**
858     * Returns the avatar URL for a user, or an empty string if there isn't a valid avatar.
859     *
860     * @param string $email The user's email.
861     * @param int    $avatar_size The size of the avatar in pixels.
862     *
863     * @todo Provide a non-WP.com option.
864     *
865     * @return string
866     */
867    protected function get_avatar_url( $email, $avatar_size = 96 ) {
868        $avatar_url = function_exists( 'wpcom_get_avatar_url' ) ? wpcom_get_avatar_url( $email, $avatar_size ) : '';
869        if ( ! $avatar_url || is_wp_error( $avatar_url ) ) {
870            return '';
871        }
872
873        return esc_url_raw( htmlspecialchars_decode( $avatar_url[0], ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 ) );
874    }
875
876    /**
877     * Return extra post permalink suggestions in an array including the 'permalink_URL' and the 'suggested_slug'.
878     *
879     * @param string $title The current post title.
880     *
881     * @return array
882     */
883    public function get_permalink_suggestions( $title ) {
884        $suggestions = array();
885        list( $suggestions['permalink_URL'], $suggestions['suggested_slug'] ) = get_sample_permalink( $this->post->ID, $title );
886        return $suggestions;
887    }
888
889    /**
890     * Returns an object with formatted taxonomy information such as slug and meta information.
891     *
892     * Otherwise, returns an error if the edit or display permissions aren't correct.
893     *
894     * @param WP_Term $taxonomy The current taxonomy.
895     * @param string  $taxonomy_type The current taxonomy type, for example 'category'.
896     * @param string  $context The current context, for example 'edit' or 'display'.
897     *
898     * @return object
899     */
900    private function format_taxonomy( $taxonomy, $taxonomy_type, $context ) {
901        // Permissions.
902        switch ( $context ) {
903            case 'edit':
904                $tax = get_taxonomy( $taxonomy_type );
905                if ( ! current_user_can( $tax->cap->edit_terms ) ) {
906                    return new WP_Error( 'unauthorized', 'User cannot edit taxonomy', 403 );
907                }
908                break;
909            case 'display':
910                if ( ( new Status() )->is_private_site() && ! current_user_can( 'read' ) ) {
911                    return new WP_Error( 'unauthorized', 'User cannot view taxonomy', 403 );
912                }
913                break;
914            default:
915                return new WP_Error( 'invalid_context', 'Invalid API CONTEXT', 400 );
916        }
917
918        $response                = array();
919        $response['ID']          = (int) $taxonomy->term_id;
920        $response['name']        = (string) $taxonomy->name;
921        $response['slug']        = (string) $taxonomy->slug;
922        $response['description'] = (string) $taxonomy->description;
923        $response['post_count']  = (int) $taxonomy->count;
924
925        if ( is_taxonomy_hierarchical( $taxonomy_type ) ) {
926            $response['parent'] = (int) $taxonomy->parent;
927        }
928
929        $response['meta'] = (object) array(
930            'links' => (object) array(
931                'self' => (string) $this->links->get_taxonomy_link( $this->site->get_id(), $taxonomy->slug, $taxonomy_type ),
932                'help' => (string) $this->links->get_taxonomy_link( $this->site->get_id(), $taxonomy->slug, $taxonomy_type, 'help' ),
933                'site' => (string) $this->links->get_site_link( $this->site->get_id() ),
934            ),
935        );
936
937        return (object) $response;
938    }
939
940    /**
941     * Builds and returns the media item's details.
942     *
943     * @param int $media_id The media item ID.
944     * @todo: factor this out into site.
945     *
946     * @return object
947     */
948    private function get_media_item_v1_1( $media_id ) {
949        $media_item = get_post( $media_id );
950
951        if ( ! $media_item || is_wp_error( $media_item ) ) {
952            return new WP_Error( 'unknown_media', 'Unknown Media', 404 );
953        }
954
955        $file      = basename( wp_get_attachment_url( $media_item->ID ) );
956        $file_info = pathinfo( $file );
957        $ext       = isset( $file_info['extension'] ) ? $file_info['extension'] : '';
958
959        $response = array(
960            'ID'          => $media_item->ID,
961            'URL'         => wp_get_attachment_url( $media_item->ID ),
962            'guid'        => $media_item->guid,
963            'date'        => (string) WPCOM_JSON_API_Date::format_date( $media_item->post_date_gmt, $media_item->post_date ),
964            'post_ID'     => $media_item->post_parent,
965            'author_ID'   => (int) $media_item->post_author,
966            'file'        => $file,
967            'mime_type'   => $media_item->post_mime_type,
968            'extension'   => $ext,
969            'title'       => $media_item->post_title,
970            'caption'     => $media_item->post_excerpt,
971            'description' => $media_item->post_content,
972            'alt'         => get_post_meta( $media_item->ID, '_wp_attachment_image_alt', true ),
973            'thumbnails'  => array(),
974        );
975
976        if ( in_array( $ext, array( 'jpg', 'jpeg', 'png', 'gif', 'webp' ), true ) ) {
977            $metadata = wp_get_attachment_metadata( $media_item->ID );
978            if ( isset( $metadata['height'] ) && isset( $metadata['width'] ) ) {
979                $response['height'] = $metadata['height'];
980                $response['width']  = $metadata['width'];
981            }
982
983            if ( isset( $metadata['sizes'] ) ) {
984                /**
985                 * Filter the thumbnail sizes available for each attachment ID.
986                 *
987                 * @module json-api
988                 *
989                 * @since 3.9.0
990                 *
991                 * @param array $metadata['sizes'] Array of thumbnail sizes available for a given attachment ID.
992                 * @param int   $media_id The media item ID.
993                 */
994                $sizes = apply_filters( 'rest_api_thumbnail_sizes', $metadata['sizes'], $media_id );
995                if ( is_array( $sizes ) ) {
996                    foreach ( $sizes as $size => $size_details ) {
997                        if ( isset( $size_details['file'] ) ) {
998                            $response['thumbnails'][ $size ] = dirname( $response['URL'] ) . '/' . $size_details['file'];
999                        }
1000                    }
1001                }
1002            }
1003
1004            if ( isset( $metadata['image_meta'] ) ) {
1005                $response['exif'] = $metadata['image_meta'];
1006            }
1007        }
1008
1009        if ( in_array( $ext, array( 'mp3', 'm4a', 'wav', 'ogg' ), true ) ) {
1010            $metadata = wp_get_attachment_metadata( $media_item->ID );
1011            if ( isset( $metadata['length'] ) ) {
1012                $response['length'] = $metadata['length'];
1013            }
1014
1015            $response['exif'] = $metadata;
1016        }
1017
1018        if ( in_array( $ext, array( 'ogv', 'mp4', 'mov', 'wmv', 'avi', 'mpg', '3gp', '3g2', 'm4v' ), true ) ) {
1019            $metadata = wp_get_attachment_metadata( $media_item->ID );
1020            if ( isset( $metadata['height'] ) && isset( $metadata['width'] ) ) {
1021                $response['height'] = $metadata['height'];
1022                $response['width']  = $metadata['width'];
1023            }
1024
1025            if ( isset( $metadata['length'] ) ) {
1026                $response['length'] = $metadata['length'];
1027            }
1028
1029            if ( empty( $response['length'] ) && isset( $metadata['duration'] ) ) {
1030                $response['length'] = (int) $metadata['duration'];
1031            }
1032
1033            if ( empty( $response['length'] ) && isset( $metadata['videopress']['duration'] ) ) {
1034                $response['length'] = ceil( $metadata['videopress']['duration'] / 1000 );
1035            }
1036
1037            // add VideoPress info.
1038            if ( function_exists( 'video_get_info_by_blogpostid' ) ) {
1039                $info = video_get_info_by_blogpostid( $this->site->get_id(), $media_id );
1040
1041                // Thumbnails.
1042                if ( function_exists( 'video_format_done' ) && function_exists( 'video_image_url_by_guid' ) ) {
1043                    $response['thumbnails'] = array(
1044                        'fmt_hd'  => '',
1045                        'fmt_dvd' => '',
1046                        'fmt_std' => '',
1047                    );
1048                    foreach ( $response['thumbnails'] as $size => $thumbnail_url ) {
1049                        if ( video_format_done( $info, $size ) ) {
1050                            $response['thumbnails'][ $size ] = video_image_url_by_guid( $info->guid, $size );
1051                        } else {
1052                            unset( $response['thumbnails'][ $size ] );
1053                        }
1054                    }
1055                }
1056
1057                $response['videopress_guid']            = $info->guid ?? null;
1058                $response['videopress_processing_done'] = true;
1059                $response['videopress_processing_done'] = isset( $info->finish_date_gmt ) && '0000-00-00 00:00:00' !== $info->finish_date_gmt ? $info->finish_date_gmt : false;
1060            }
1061        }
1062
1063        $response['thumbnails'] = (object) $response['thumbnails'];
1064
1065        $response['meta'] = (object) array(
1066            'links' => (object) array(
1067                'self' => (string) $this->links->get_media_link( $this->site->get_id(), $media_id ),
1068                'help' => (string) $this->links->get_media_link( $this->site->get_id(), $media_id, 'help' ),
1069                'site' => (string) $this->links->get_site_link( $this->site->get_id() ),
1070            ),
1071        );
1072
1073        // add VideoPress link to the meta.
1074        if ( in_array( $ext, array( 'ogv', 'mp4', 'mov', 'wmv', 'avi', 'mpg', '3gp', '3g2', 'm4v' ), true ) ) {
1075            if ( function_exists( 'video_get_info_by_blogpostid' ) ) {
1076                $response['meta']->links->videopress = (string) $this->links->get_link( '/videos/%s', $response['videopress_guid'], '' );
1077            }
1078        }
1079
1080        if ( $media_item->post_parent > 0 ) {
1081            $response['meta']->links->parent = (string) $this->links->get_post_link( $this->site->get_id(), $media_item->post_parent );
1082        }
1083
1084        return (object) $response;
1085    }
1086
1087    /**
1088     * Temporary wrapper around maybe_unserialize() to catch exceptions thrown by unserialize().
1089     *
1090     * Can be removed after https://core.trac.wordpress.org/ticket/45895 lands in Core.
1091     *
1092     * @param  string $original Serialized string.
1093     *
1094     * @return string Unserialized string or original string if an exception was raised.
1095     **/
1096    protected function safe_maybe_unserialize( $original ) {
1097        try {
1098            return maybe_unserialize( $original );
1099        } catch ( Exception $e ) {
1100            return $original;
1101        }
1102    }
1103}