Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
159 / 159
100.00% covered (success)
100.00%
7 / 7
CRAP
100.00% covered (success)
100.00%
1 / 1
Settings_Controller
100.00% covered (success)
100.00%
159 / 159
100.00% covered (success)
100.00%
7 / 7
37
100.00% covered (success)
100.00%
1 / 1
 register_routes
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
1
 get_item
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 update_item
100.00% covered (success)
100.00%
39 / 39
100.00% covered (success)
100.00%
1 / 1
15
 available_settings
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
14
 read
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 get_item_schema
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
2
 template_placements_schema
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * The settings route behind Settings > Sharing.
4 *
5 * @package automattic/jetpack-sharing-likes
6 */
7
8declare( strict_types = 1 );
9
10namespace Automattic\Jetpack\Sharing_Likes\REST;
11
12use Automattic\Jetpack\Sharing_Likes\Hooked_Blocks\Template_Placements;
13use Automattic\Jetpack\Sharing_Likes\Settings\Comment_Likes_Section;
14use Automattic\Jetpack\Sharing_Likes\Settings\Environment;
15use Automattic\Jetpack\Sharing_Likes\Settings\Likes_Options;
16use Automattic\Jetpack\Sharing_Likes\Settings\Likes_Section;
17use Automattic\Jetpack\Sharing_Likes\Settings\Placement_Section;
18use Automattic\Jetpack\Sharing_Likes\Settings\Section_State;
19use Automattic\Jetpack\Sharing_Likes\Settings\Sharing_Options;
20use Automattic\Jetpack\Sharing_Likes\Settings\Sharing_Resources;
21use Automattic\Jetpack\Sharing_Likes\Settings\Sharing_Section;
22use Automattic\Jetpack\Sharing_Likes\Settings\Twitter_Site_Tag;
23use WP_Error;
24use WP_REST_Request;
25use WP_REST_Response;
26use WP_REST_Server;
27
28/**
29 * Reads and saves every setting the screen shows, and only those.
30 *
31 * A setting its section does not render is left out of reads and refused on writes,
32 * so the API offers no way back where `BLOCK_CALL_TO_ACTION` deliberately has none.
33 */
34final class Settings_Controller extends Controller {
35
36    /**
37     * The options `Sharing_Options::update()` saves together.
38     */
39    private const SHARING_OPTIONS = array( 'button_style', 'sharing_label' );
40
41    /**
42     * Each feature's template placements, by setting name.
43     */
44    private const TEMPLATE_PLACEMENTS = array(
45        'sharing_buttons_auto_add' => Template_Placements::FEATURE_SHARING,
46        'likes_auto_add'           => Template_Placements::FEATURE_LIKES,
47    );
48
49    /**
50     * Register the route.
51     */
52    public function register_routes() {
53        register_rest_route(
54            $this->namespace,
55            '/' . Endpoints::BASE . '/settings',
56            array(
57                array(
58                    'methods'             => WP_REST_Server::READABLE,
59                    'callback'            => array( $this, 'get_item' ),
60                    'permission_callback' => array( $this, 'permission_check' ),
61                ),
62                array(
63                    'methods'             => WP_REST_Server::EDITABLE,
64                    'callback'            => array( $this, 'update_item' ),
65                    'permission_callback' => array( $this, 'permission_check' ),
66                    // Core skips its validate callback for `null`, then sanitizes it to `false` or `''`; this one validates first.
67                    'args'                => array_map(
68                        function ( $arg ) {
69                            return array_merge( $arg, array( 'sanitize_callback' => 'rest_parse_request_arg' ) );
70                        },
71                        $this->get_endpoint_args_for_item_schema( WP_REST_Server::EDITABLE )
72                    ),
73                ),
74            )
75        );
76    }
77
78    /**
79     * Every setting this site's screen shows.
80     *
81     * @param WP_REST_Request $request Request.
82     * @return WP_REST_Response
83     */
84    public function get_item( $request ) {
85        unset( $request );
86
87        return rest_ensure_response( self::read( self::available_settings() ) );
88    }
89
90    /**
91     * Save the settings the request carries and leave every other one as stored.
92     *
93     * @param WP_REST_Request $request Request.
94     * @return WP_REST_Response|WP_Error
95     */
96    public function update_item( $request ) {
97        $sent = array();
98
99        foreach ( array_keys( $this->get_item_schema()['properties'] ) as $key ) {
100            if ( $request->has_param( $key ) ) {
101                $sent[ $key ] = $request->get_param( $key );
102            }
103        }
104
105        $unavailable = array_values( array_diff( array_keys( $sent ), self::available_settings() ) );
106
107        if ( $unavailable ) {
108            return new WP_Error(
109                'rest_sharing_likes_setting_unavailable',
110                /* translators: %s: comma-separated list of setting names. */
111                sprintf( __( 'These settings are not available on this site: %s.', 'jetpack-sharing-likes' ), implode( ', ', $unavailable ) ),
112                array(
113                    'status' => 400,
114                    'params' => $unavailable,
115                )
116            );
117        }
118
119        // First, because it is the one write that can fail, and a failure should leave everything else as it was.
120        if ( isset( $sent['comment_likes_enabled'] ) && ! Comment_Likes_Section::update( $sent['comment_likes_enabled'] ) ) {
121            return new WP_Error(
122                'rest_sharing_likes_comment_likes_unchanged',
123                __( 'Comment Likes could not be switched on or off on this site.', 'jetpack-sharing-likes' ),
124                array( 'status' => 409 )
125            );
126        }
127
128        $sharing = array_intersect_key( $sent, array_flip( self::SHARING_OPTIONS ) );
129
130        if ( $sharing ) {
131            // `set_global_options()` unslashes the label, as it was written for `$_POST`.
132            if ( isset( $sharing['sharing_label'] ) ) {
133                $sharing['sharing_label'] = wp_slash( $sharing['sharing_label'] );
134            }
135
136            Sharing_Options::update( $sharing );
137        }
138
139        // After the sharing options, which rewrite the global array placement lives in.
140        if ( isset( $sent['show'] ) ) {
141            Placement_Section::update( $sent['show'] );
142        }
143
144        if ( isset( $sent['likes_enabled'] ) ) {
145            Likes_Options::set_likes_enabled( $sent['likes_enabled'] );
146        }
147
148        if ( isset( $sent['reblogs_enabled'] ) ) {
149            Likes_Options::set_reblogs_enabled( $sent['reblogs_enabled'] );
150        }
151
152        if ( isset( $sent['twitter_site_tag'] ) ) {
153            Twitter_Site_Tag::update( $sent['twitter_site_tag'] );
154        }
155
156        if ( isset( $sent['disable_resources'] ) ) {
157            Sharing_Resources::update( $sent['disable_resources'] );
158        }
159
160        foreach ( self::TEMPLATE_PLACEMENTS as $setting => $feature ) {
161            if ( isset( $sent[ $setting ] ) ) {
162                Template_Placements::update( $feature, $sent[ $setting ] );
163            }
164        }
165
166        return $this->get_item( $request );
167    }
168
169    /**
170     * The settings the screen shows on this site, following the sections that render them.
171     *
172     * @return string[]
173     */
174    private static function available_settings(): array {
175        $sharing_state        = Sharing_Section::state();
176        $likes_state          = Likes_Section::state();
177        $likes_configure      = Section_State::configures( $likes_state );
178        $comment_likes_follow = Environment::comment_likes_follow_likes_settings();
179        $settings             = array();
180
181        // With the Like buttons section showing no options, the Comment Likes section carries the sitewide default.
182        if ( $likes_configure || $comment_likes_follow ) {
183            $settings[] = 'likes_enabled';
184        }
185
186        if ( $likes_configure && Environment::is_simple_site() ) {
187            $settings[] = 'reblogs_enabled';
188        }
189
190        // Comments have no Like block to move to, so no section variant takes this one away.
191        if ( Environment::likes_supported() ) {
192            $settings[] = 'comment_likes_enabled';
193        }
194
195        if ( Sharing_Options::is_available() && Section_State::configures( $sharing_state ) ) {
196            array_push( $settings, ...self::SHARING_OPTIONS );
197        }
198
199        if ( Section_State::shows_placement( $sharing_state, $likes_state, $comment_likes_follow ) ) {
200            $settings[] = 'show';
201        }
202
203        if ( Twitter_Site_Tag::is_available() ) {
204            $settings[] = 'twitter_site_tag';
205        }
206
207        if ( Sharing_Resources::is_available() ) {
208            $settings[] = 'disable_resources';
209        }
210
211        // Only the React screen shows these, and only where the legacy feature is off for good, so they cannot reopen it.
212        if ( Section_State::BLOCK_CALL_TO_ACTION === $sharing_state ) {
213            $settings[] = 'sharing_buttons_auto_add';
214        }
215
216        // Offline mode can reach this variant, but the screen then says a connection is needed, and the hooks add nothing.
217        if ( Section_State::BLOCK_CALL_TO_ACTION === $likes_state && Environment::likes_supported() ) {
218            $settings[] = 'likes_auto_add';
219        }
220
221        return $settings;
222    }
223
224    /**
225     * Current values of the given settings.
226     *
227     * @param string[] $settings Setting names.
228     * @return array<string, mixed>
229     */
230    private static function read( array $settings ): array {
231        $values = array();
232
233        if ( array_intersect( self::SHARING_OPTIONS, $settings ) ) {
234            $values = Sharing_Options::get();
235            // Stored through `wp_kses()`, which encodes a bare `&`; the screen shows it decoded.
236            $values['sharing_label'] = wp_specialchars_decode( $values['sharing_label'], ENT_QUOTES );
237        }
238
239        $values['likes_enabled']         = Likes_Options::likes_enabled_sitewide();
240        $values['reblogs_enabled']       = Likes_Options::reblogs_enabled_sitewide();
241        $values['comment_likes_enabled'] = Environment::comment_likes_enabled();
242        $values['show']                  = Placement_Section::selected_post_types();
243        $values['twitter_site_tag']      = (string) get_option( Twitter_Site_Tag::OPTION, '' );
244        $values['disable_resources']     = (bool) get_option( Sharing_Resources::OPTION );
245
246        foreach ( self::TEMPLATE_PLACEMENTS as $setting => $feature ) {
247            $values[ $setting ] = Template_Placements::get( $feature );
248        }
249
250        return array_intersect_key( $values, array_flip( $settings ) );
251    }
252
253    /**
254     * The settings record.
255     *
256     * @return array<string, mixed>
257     */
258    public function get_item_schema() {
259        if ( $this->schema ) {
260            return $this->schema;
261        }
262
263        $this->schema = array(
264            '$schema'    => 'http://json-schema.org/draft-04/schema#',
265            'title'      => 'sharing-likes-settings',
266            'type'       => 'object',
267            'properties' => array(
268                'likes_enabled'            => array(
269                    'description' => __( 'Whether posts show Like buttons.', 'jetpack-sharing-likes' ),
270                    'type'        => 'boolean',
271                ),
272                'reblogs_enabled'          => array(
273                    'description' => __( 'Whether posts show Reblog buttons. WordPress.com Simple only.', 'jetpack-sharing-likes' ),
274                    'type'        => 'boolean',
275                ),
276                'comment_likes_enabled'    => array(
277                    'description' => __( 'Whether readers can like individual comments.', 'jetpack-sharing-likes' ),
278                    'type'        => 'boolean',
279                ),
280                'button_style'             => array(
281                    'description' => __( 'How sharing buttons look.', 'jetpack-sharing-likes' ),
282                    'type'        => 'string',
283                    'enum'        => Sharing_Options::BUTTON_STYLES,
284                ),
285                'sharing_label'            => array(
286                    'description' => __( 'Text shown above the sharing buttons.', 'jetpack-sharing-likes' ),
287                    'type'        => 'string',
288                ),
289                'show'                     => array(
290                    'description' => __( 'Post types the buttons appear on, plus "index" for the front page, archives and search results.', 'jetpack-sharing-likes' ),
291                    'type'        => 'array',
292                    'items'       => array( 'type' => 'string' ),
293                ),
294                'twitter_site_tag'         => array(
295                    'description' => __( 'X (Twitter) username of the site owner, without the @.', 'jetpack-sharing-likes' ),
296                    'type'        => 'string',
297                ),
298                'disable_resources'        => array(
299                    'description' => __( 'Whether the sharing buttons skip their own CSS and JS.', 'jetpack-sharing-likes' ),
300                    'type'        => 'boolean',
301                ),
302                'sharing_buttons_auto_add' => self::template_placements_schema(
303                    __( 'Where the Sharing Buttons block is added to single post and page templates: before the post content or after it.', 'jetpack-sharing-likes' )
304                ),
305                'likes_auto_add'           => self::template_placements_schema(
306                    __( 'Where the Like block is added to single post and page templates: before the post content or after it.', 'jetpack-sharing-likes' )
307                ),
308            ),
309        );
310
311        return $this->schema;
312    }
313
314    /**
315     * One feature's template placements: one side of the post content, or none.
316     *
317     * Both sides are refused rather than trimmed to one, as `Template_Placements::update()` would.
318     *
319     * @param string $description Setting description.
320     * @return array<string, mixed>
321     */
322    private static function template_placements_schema( string $description ): array {
323        return array(
324            'description' => $description,
325            'type'        => 'array',
326            'items'       => array(
327                'type' => 'string',
328                'enum' => Template_Placements::PLACEMENTS,
329            ),
330            'maxItems'    => 1,
331        );
332    }
333}