Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
63.48% covered (warning)
63.48%
73 / 115
60.00% covered (warning)
60.00%
6 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
Proposal_Store
63.48% covered (warning)
63.48%
73 / 115
60.00% covered (warning)
60.00%
6 / 10
154.61
0.00% covered (danger)
0.00%
0 / 1
 register
7.14% covered (danger)
7.14%
2 / 28
0.00% covered (danger)
0.00%
0 / 1
10.21
 get
80.00% covered (warning)
80.00%
4 / 5
0.00% covered (danger)
0.00%
0 / 1
4.13
 get_by_uuid
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 posts_with_status
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
1
 from_post
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
6
 is_valid_payload
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
21
 hash
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 encode
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 write
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
4.03
 preserve_payload
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2/**
3 * Storage for proposals: the post type, statuses and payload.
4 *
5 * @package automattic/jetpack-mu-wpcom
6 */
7
8namespace Automattic\Jetpack\Jetpack_Mu_Wpcom\Proposals;
9
10use WP_Error;
11use WP_Post;
12
13/**
14 * Reads and writes proposal posts, whose post_content holds a JSON payload of typed items.
15 */
16class Proposal_Store {
17
18    const POST_TYPE = 'jetpack_proposal';
19
20    const PAYLOAD_VERSION = 2;
21
22    const MAX_ITEMS = 20;
23
24    const MAX_PAYLOAD_BYTES = 1048576;
25
26    const STATUSES = array(
27        'pending'   => 'jpp-pending',
28        'applied'   => 'jpp-applied',
29        'rejected'  => 'jpp-rejected',
30        'stale'     => 'jpp-stale',
31        'discarded' => 'jpp-discarded',
32    );
33
34    /** Who applied or rejected the proposal, and the outcome. */
35    const REVIEW_META = '_jetpack_proposal_review';
36
37    /** Keys a stored item may have. */
38    const ITEM_KEYS = array( 'id', 'type', 'target', 'base', 'change' );
39
40    /**
41     * Register the post type and statuses, lazily, since WordPress.com calls this class after switch_to_blog().
42     *
43     * Its capabilities are granted to no role, so only this class can write a proposal.
44     */
45    public static function register(): void {
46        if ( post_type_exists( self::POST_TYPE ) ) {
47            return;
48        }
49
50        register_post_type(
51            self::POST_TYPE,
52            array(
53                'label'               => 'Proposals',
54                'public'              => false,
55                'show_ui'             => false,
56                'show_in_rest'        => false,
57                'show_in_nav_menus'   => false,
58                'exclude_from_search' => true,
59                'can_export'          => false,
60                'rewrite'             => false,
61                'query_var'           => false,
62                'capability_type'     => array( 'jetpack_proposal', 'jetpack_proposals' ),
63                'map_meta_cap'        => true,
64                'supports'            => array( 'title', 'author' ),
65            )
66        );
67
68        foreach ( self::STATUSES as $status ) {
69            register_post_status(
70                $status,
71                array(
72                    'internal'            => true,
73                    'public'              => false,
74                    'exclude_from_search' => true,
75                )
76            );
77        }
78    }
79
80    /**
81     * Get a proposal by ID.
82     *
83     * @param int $proposal_id Proposal post ID.
84     * @return array|null
85     */
86    public static function get( int $proposal_id ): ?array {
87        self::register();
88
89        $post = $proposal_id > 0 ? get_post( $proposal_id ) : null;
90        if ( ! $post || self::POST_TYPE !== $post->post_type ) {
91            return null;
92        }
93
94        return self::from_post( $post );
95    }
96
97    /**
98     * Get a proposal by its preview token. Numeric IDs are never accepted.
99     *
100     * @param string $uuid A v4 UUID.
101     * @return array|null
102     */
103    public static function get_by_uuid( string $uuid ): ?array {
104        if ( ! wp_is_uuid( $uuid, 4 ) ) {
105            return null;
106        }
107
108        self::register();
109
110        $posts = get_posts(
111            array(
112                'post_type'        => self::POST_TYPE,
113                'post_status'      => array_values( self::STATUSES ),
114                'name'             => $uuid,
115                'posts_per_page'   => 1,
116                'no_found_rows'    => true,
117                'suppress_filters' => true,
118            )
119        );
120
121        return $posts ? self::from_post( $posts[0] ) : null;
122    }
123
124    /**
125     * Proposals with any of these statuses, newest first.
126     *
127     * @param string[] $statuses Keys of STATUSES.
128     * @param int      $limit    At most this many.
129     * @return WP_Post[]
130     */
131    public static function posts_with_status( array $statuses, int $limit ): array {
132        self::register();
133
134        return get_posts(
135            array(
136                'post_type'        => self::POST_TYPE,
137                'post_status'      => array_values( array_intersect_key( self::STATUSES, array_flip( $statuses ) ) ),
138                'posts_per_page'   => $limit,
139                'orderby'          => 'ID',
140                'order'            => 'DESC',
141                'no_found_rows'    => true,
142                'suppress_filters' => true,
143            )
144        );
145    }
146
147    /**
148     * Build the proposal array from its post.
149     *
150     * @param WP_Post $post Proposal post.
151     * @return array{id: int, uuid: string, title: string, author: int, status: string, created_gmt: string, modified_gmt: string, hash: string, items: array<int, array>, review: array}
152     */
153    public static function from_post( WP_Post $post ): array {
154        $payload = json_decode( $post->post_content, true );
155        $items   = is_array( $payload ) && self::PAYLOAD_VERSION === ( $payload['version'] ?? null ) && self::is_valid_payload( $payload['items'] ?? null ) ? $payload['items'] : array();
156        $status  = array_search( $post->post_status, self::STATUSES, true );
157        $review  = get_post_meta( $post->ID, self::REVIEW_META, true );
158
159        return array(
160            'id'           => (int) $post->ID,
161            'uuid'         => $post->post_name,
162            'title'        => $post->post_title,
163            'author'       => (int) $post->post_author,
164            // A status set outside this feature, such as trash, closes the proposal rather than reopening it.
165            'status'       => false === $status ? 'discarded' : $status,
166            'created_gmt'  => $post->post_date_gmt,
167            'modified_gmt' => $post->post_modified_gmt,
168            'hash'         => self::hash( $post->post_content ),
169            'items'        => $items,
170            'review'       => is_array( $review ) ? $review : array(),
171        );
172    }
173
174    /**
175     * Whether stored items are a payload the engine could have produced. Anything else reads as empty.
176     *
177     * @param mixed $items Decoded payload items.
178     */
179    public static function is_valid_payload( $items ): bool {
180        if ( ! is_array( $items ) || ! $items || count( $items ) > self::MAX_ITEMS || ! array_is_list( $items ) ) {
181            return false;
182        }
183
184        $handlers = Proposals::handlers();
185        $ids      = array();
186        $targets  = array();
187
188        foreach ( $items as $item ) {
189            if (
190                ! is_array( $item )
191                || array_diff( array_keys( $item ), self::ITEM_KEYS )
192                || ! is_string( $item['id'] ?? null ) || ! preg_match( '/^i[1-9][0-9]*$/D', $item['id'] ) || isset( $ids[ $item['id'] ] )
193                || ! is_string( $item['type'] ?? null ) || ! isset( $handlers[ $item['type'] ] )
194                || ! is_array( $item['target'] ?? null ) || ! is_array( $item['base'] ?? null ) || ! is_array( $item['change'] ?? null )
195            ) {
196                return false;
197            }
198            $handler = $handlers[ $item['type'] ];
199            if ( ! $handler->is_valid( $item ) ) {
200                return false;
201            }
202            $ids[ $item['id'] ] = true;
203
204            foreach ( $handler->targets( $item ) as $target ) {
205                if ( ! is_string( $target ) || '' === $target || isset( $targets[ $target ] ) ) {
206                    return false;
207                }
208                $targets[ $target ] = true;
209            }
210        }
211
212        return true;
213    }
214
215    /**
216     * The version identifier a person approves.
217     *
218     * @param string $content Stored payload.
219     */
220    public static function hash( string $content ): string {
221        return hash( 'sha256', $content );
222    }
223
224    /**
225     * Encode items as a payload.
226     *
227     * @param array $items Items.
228     */
229    public static function encode( array $items ): string {
230        return (string) wp_json_encode(
231            array(
232                'version' => self::PAYLOAD_VERSION,
233                'items'   => $items,
234            ),
235            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
236        );
237    }
238
239    /**
240     * Insert or update a proposal post without content filters rewriting the JSON. The handlers sanitized its values.
241     *
242     * @param array $postarr Post data.
243     * @return int|WP_Error Proposal ID.
244     */
245    public static function write( array $postarr ) {
246        self::register();
247
248        if ( isset( $postarr['post_content'] ) && strlen( $postarr['post_content'] ) > self::MAX_PAYLOAD_BYTES ) {
249            return new WP_Error( 'proposal_too_large', 'Nothing was saved: the proposal would take more than 1 MB to store. Propose fewer posts at a time; a single post\'s content must stay well under 1 MB.' );
250        }
251
252        add_filter( 'wp_insert_post_data', array( __CLASS__, 'preserve_payload' ), 5, 3 );
253        try {
254            return isset( $postarr['ID'] )
255                ? wp_update_post( wp_slash( $postarr ), true )
256                : wp_insert_post( wp_slash( $postarr ), true );
257        } finally {
258            remove_filter( 'wp_insert_post_data', array( __CLASS__, 'preserve_payload' ), 5 );
259        }
260    }
261
262    /**
263     * Keep the payload exactly as encoded. Mirrors
264     * WP_Customize_Manager::preserve_insert_changeset_post_content().
265     *
266     * @param array $data                Sanitized post data.
267     * @param array $postarr             Post data.
268     * @param array $unsanitized_postarr Post data before sanitizing.
269     * @return array
270     */
271    public static function preserve_payload( array $data, array $postarr, array $unsanitized_postarr ): array { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Filter signature.
272        if ( self::POST_TYPE === $data['post_type'] && isset( $unsanitized_postarr['post_content'] ) ) {
273            $data['post_content'] = $unsanitized_postarr['post_content'];
274        }
275        return $data;
276    }
277}