Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
19.94% covered (danger)
19.94%
65 / 326
11.36% covered (danger)
11.36%
5 / 44
CRAP
n/a
0 / 0
Private_Site\is_module_active
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Private_Site\admin_init
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
90
Private_Site\init
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
Private_Site\muplugins_loaded
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
Private_Site\fetch_option_from_wpcom
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
Private_Site\site_is_coming_soon
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
Private_Site\site_is_public_coming_soon
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
Private_Site\site_launch_status
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
20
Private_Site\is_launched
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\site_is_private
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
Private_Site\filter_jetpack_is_private_site
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
Private_Site\should_prevent_site_access
66.67% covered (warning)
66.67%
6 / 9
0.00% covered (danger)
0.00%
0 / 1
10.37
Private_Site\register_additional_jetpack_xmlrpc_methods
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
Private_Site\get_closest_thumbnail_size_url
44.44% covered (danger)
44.44%
4 / 9
0.00% covered (danger)
0.00%
0 / 1
12.17
Private_Site\get_read_access_cookies
96.97% covered (success)
96.97%
32 / 33
0.00% covered (danger)
0.00%
0 / 1
4
Private_Site\is_jetpack_admin_ajax_request
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
42
Private_Site\send_access_denied_error_response
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
Private_Site\parse_request
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
Private_Site\original_request_url
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
Private_Site\cache_option_on_update_site_settings
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
Private_Site\maybe_print_robots_txt
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
Private_Site\rest_dispatch_request
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
20
Private_Site\xmlrpc_methods_limit_to_allowed_list
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
12
Private_Site\is_private_blog_user
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
Private_Site\blog_user_can
33.33% covered (danger)
33.33%
3 / 9
0.00% covered (danger)
0.00%
0 / 1
5.67
Private_Site\mask_site_name
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
20
Private_Site\remove_mask_site_name_filter
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\preprocess_comment
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
Private_Site\is_jetpack_connected
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
6
Private_Site\is_site_preview
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\site_preview_source
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
156
Private_Site\access_denied_template_path
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
56
Private_Site\remove_privacy_option_from_whitelist
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\should_update_privacy_selector
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\private_robots_txt
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\rename_subscriber_role_to_viewer
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
12
Private_Site\translate_viewer_role
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
4.59
Private_Site\private_no_pinning
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\hide_opml
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
Private_Site\filter_jetpack_active_modules
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\filter_jetpack_get_available_modules
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
Private_Site\use_classic_editor_if_requested
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
30
Private_Site\disable_classic_editor_plugin_when_needed
37.50% covered (danger)
37.50%
3 / 8
0.00% covered (danger)
0.00%
0 / 1
7.91
Private_Site\should_override_editor_with_classic_editor
36.36% covered (danger)
36.36%
4 / 11
0.00% covered (danger)
0.00%
0 / 1
19.63
1<?php
2/**
3 * Private Site
4 * Functionality to make sites private and only accessible to members with appropriate capabilities.
5 *
6 * @package private-site
7 */
8
9namespace Private_Site;
10
11use Automattic\Jetpack\Connection\Rest_Authentication;
12use Jetpack;
13use WP_Error;
14use WP_REST_Request;
15use function esc_html_e;
16use function get_current_blog_id;
17use function get_option;
18use function remove_filter;
19use function status_header;
20use function wp_get_current_user;
21use function wp_send_json_error;
22
23/**
24 * We disable some Jetpack modules if the site is private and atomic
25 *
26 * !!! KEEP THIS LIST IN SYNC WITH THE LIST ON WPCOM !!!
27 *
28 * @see private_blog_filter_jetpack_active_modules in wp-content/mu-plugins/private-blog.php (update this to an actual link when D41356-code lands)
29 */
30const DISABLED_JETPACK_MODULES_WHEN_PRIVATE = array(
31    'publicize',
32    'sharedaddy',
33    'json-api',
34    'enhanced-distribution',
35    'google-analytics',
36    'photon',
37    'photon-cdn',
38    'sitemaps',
39    'verification-tools',
40    'wordads',
41);
42
43/**
44 * This function was used when the feature was in testing. Currently we're trying it for a some WP.com users.
45 * Wpcomsh is not aware of any test groups so this function just says return true for now. Once the entire feature
46 * is ready to be rolled out to 100% of users, it's okay to completely remove this function and any checks.
47 */
48function is_module_active() {
49    return true;
50}
51
52/**
53 * Setup when wp-admin gets initialized.
54 */
55function admin_init() {
56    if ( ! is_module_active() ) {
57        return;
58    }
59
60    /*
61     * Don't add the action when we don't intend to alter core behavior.
62     * The mere presence of a `blog_privacy_selector` hook changes things!
63     *
64     * @see https://github.com/WordPress/wordpress-develop/blob/fd479f953731bbf522b32b9d95eeb68bc455c418/src/wp-admin/options-reading.php#L178-L202
65     */
66    if ( ( is_jetpack_connected() || site_is_private() ) && should_update_privacy_selector() ) {
67        // Prevent wp-admin from touching blog_public option.
68        add_filter( 'allowed_options', '\Private_Site\remove_privacy_option_from_whitelist' );
69    }
70
71    if ( should_override_editor_with_classic_editor() ) {
72        // Classic editor for private+atomic users is now handled in wp-admin instead of Calypso. @see use_classic_editor_if_requested
73        add_action( 'load-post.php', '\Private_Site\use_classic_editor_if_requested', - 1000 );
74        add_action( 'load-post-new.php', '\Private_Site\use_classic_editor_if_requested', - 1000 );
75    }
76
77    // Many AJAX actions do not execute the `parse_request` action. Catch them here.
78    if ( site_is_private() && should_prevent_site_access() && ! is_jetpack_admin_ajax_request() ) {
79        send_access_denied_error_response();
80    }
81}
82add_action( 'admin_init', '\Private_Site\admin_init' );
83
84/**
85 * Setup when WordPress gets initialized.
86 */
87function init() {
88    if ( ! is_module_active() ) {
89        return;
90    }
91
92    // Update `wpcom_coming_soon` cached value when it's updated on WP.com.
93    add_filter( 'rest_api_update_site_settings', '\Private_Site\cache_option_on_update_site_settings', 10, 2 );
94
95    if ( ! site_is_private() ) {
96        return;
97    }
98
99    // Scrutinize most requests.
100    add_action( 'parse_request', '\Private_Site\parse_request', 100 );
101
102    // Scrutinize REST API requests.
103    add_filter( 'rest_dispatch_request', '\Private_Site\rest_dispatch_request', 10, 3 );
104
105    // Prevent Pinterest pinning.
106    add_action( 'wp_head', '\Private_Site\private_no_pinning' );
107
108    // Prevent leaking site information via OPML.
109    add_action( 'opml_head', '\Private_Site\hide_opml' );
110
111    // Mask the blog name on the login screen etc.
112    add_filter( 'bloginfo', '\Private_Site\mask_site_name', 3, 2 );
113
114    // Block incoming comments for non-users.
115    add_filter( 'preprocess_comment', '\Private_Site\preprocess_comment', 0 );
116
117    // Robots requests are allowed via parse_request / maybe_print_robots_txt
118    add_filter( 'robots_txt', '\Private_Site\private_robots_txt' );
119
120    // @TODO pre_trackback_post maybe..?
121
122    // @TODO add "lock" toolbar item when private
123}
124add_action( 'init', '\Private_Site\init' );
125
126/**
127 * Jetpack-specific hooks.
128 */
129function muplugins_loaded() {
130    if ( ! is_module_active() ) {
131        return;
132    }
133
134    if ( ! site_is_private() ) {
135        return;
136    }
137
138    // Only allow Jetpack XMLRPC methods -- Jetpack handles verifying the token, request signature, etc.
139    add_filter( 'xmlrpc_methods', '\Private_Site\xmlrpc_methods_limit_to_allowed_list' );
140
141    // Register additional Jetpack XMLRPC methods.
142    add_filter( 'jetpack_xmlrpc_methods', '\Private_Site\register_additional_jetpack_xmlrpc_methods' );
143
144    // Lift the blog name mask prior to Jetpack sync activity.
145    add_action( 'jetpack_sync_before_send_queue_full_sync', '\Private_Site\remove_mask_site_name_filter' );
146    add_action( 'jetpack_sync_before_send_queue_sync', '\Private_Site\remove_mask_site_name_filter' );
147
148    // Prevent Jetpack certain modules from running while the site is private.
149    add_filter( 'jetpack_active_modules', '\Private_Site\filter_jetpack_active_modules' );
150    add_filter( 'jetpack_get_available_modules', '\Private_Site\filter_jetpack_get_available_modules' );
151    add_filter( 'jetpack_force_disable_site_accelerator', '__return_true' );
152}
153add_action( 'muplugins_loaded', '\Private_Site\muplugins_loaded' );
154
155/**
156 * Fetches an option from the Jetpack cloud site.
157 *
158 * @param string $option Name of option to be retrieved.
159 *
160 * @return mixed  Option value.
161 */
162function fetch_option_from_wpcom( $option ) {
163    if ( ! is_jetpack_connected() ) {
164        return false;
165    }
166
167    $jetpack = Jetpack::init();
168    if ( ! method_exists( $jetpack, 'get_cloud_site_options' ) ) {
169        return false;
170    }
171    $options = $jetpack->get_cloud_site_options( array( $option ) );
172
173    return $options[ $option ] ?? false;
174}
175
176/**
177 * The site is determined to be "coming soon" when both:
178 * - The site is private (@see site_is_private)
179 * - The `wpcom_coming_soon` option on the "cloud site" is truthy
180 *
181 * As such, "coming soon" is just a flavor of private sites and is always false on sites that are public.
182 *
183 * @return bool
184 */
185function site_is_coming_soon(): bool {
186    if ( ! site_is_private() ) {
187        return false;
188    }
189
190    $wpcom_coming_soon = wp_cache_get( 'wpcom_coming_soon', 'wpcomsh' );
191
192    if ( false === $wpcom_coming_soon ) {
193        $wpcom_coming_soon = (int) fetch_option_from_wpcom( 'wpcom_coming_soon' );
194        wp_cache_set( 'wpcom_coming_soon', $wpcom_coming_soon, 'wpcomsh' );
195    }
196
197    return (bool) $wpcom_coming_soon;
198}
199
200/**
201 * Checks whether a site is in public coming soon mode.
202 * The site is determined to be "public coming soon" when both:
203 * - The site is not private (@see site_is_private)
204 * - The `wpcom_public_coming_soon` option is truthy
205 *
206 * In feature-plugins/full-site-editing.php we have an option hook `wpcomsh_coming_soon_get_atomic_persistent_data()` that returns the
207 * value of Atomic persistence data.
208 *
209 * @return bool
210 */
211function site_is_public_coming_soon(): bool {
212    if ( site_is_private() ) {
213        return false;
214    }
215
216    return 1 === (int) get_option( 'wpcom_public_coming_soon' );
217}
218
219/**
220 * Sites are created as "unlaunched" and can only be launched once.
221 *
222 * @return string
223 */
224function site_launch_status(): string {
225    // We need to check for launch status for private by default sites and coming soon + public by default sites.
226    if ( ! site_is_private() && ! site_is_public_coming_soon() ) {
227        return '';
228    }
229
230    $launch_status = wp_cache_get( 'wpcom_launch_status', 'wpcomsh' );
231
232    if ( ! $launch_status ) {
233        $launch_status = (string) fetch_option_from_wpcom( 'launch-status' );
234        wp_cache_set( 'wpcom_launch_status', $launch_status, 'wpcomsh' );
235    }
236
237    return (string) $launch_status;
238}
239
240/**
241 * Whether the site is launched.
242 *
243 * @return bool
244 */
245function is_launched() {
246    return 'launched' === site_launch_status();
247}
248
249/**
250 * Hooked into filter: `pre_update_option_blog_public`.
251 *
252 * Sets a secondary option (`wpcom_blog_public_updated`) to `1` when the `blog_public` option is updated
253 * This will be used to determine that the option has been set after the launch of the Private Site module.
254 *
255 * This is in contrast to WordPress.com Simple sites which relies on the `blog_public` option.
256 *
257 * @return bool
258 */
259function site_is_private() {
260    return defined( 'AT_PRIVACY_MODEL' ) && AT_PRIVACY_MODEL === 'wp_uploads';
261}
262
263/**
264 * Hooked into filter: `jetpack_is_private_site`.
265 *
266 * Jetpack's `Status::is_private_site()` reads `blog_public`, which can say public on a site the privacy model keeps private.
267 * A stored -1 still counts: nothing here tells whether it or the privacy model is the stale one.
268 * Registered on load, before anything caches Jetpack's answer.
269 *
270 * @param bool $is_private_site Whether Jetpack considers the site private.
271 * @return bool
272 */
273function filter_jetpack_is_private_site( $is_private_site ) {
274    return $is_private_site || site_is_private();
275}
276add_filter( 'jetpack_is_private_site', '\Private_Site\filter_jetpack_is_private_site' );
277
278/**
279 * Determine if site access should be blocked for various types of requests.
280 * This function is cached for subsequent calls so we can use it gratuitously.
281 *
282 * IMPORTANT: This function assumes a site is set to private.
283 * This module is structured such that `site_is_private` is consulted prior to calling `should_prevent_site_access`
284 * You should likely do the same if you are building on to this.
285 *
286 * @return bool
287 */
288function should_prevent_site_access() {
289    static $cached;
290
291    if ( isset( $cached ) ) {
292        return $cached;
293    }
294
295    /*
296     * If Jetpack is enabled, check to see if blog token requests are authenticated before disallowing access.
297     * This allows Jetpack Sync to run for private sites.
298     */
299    if ( class_exists( 'Automattic\Jetpack\Connection\Rest_Authentication' ) && Rest_Authentication::is_signed_with_blog_token() ) {
300        return $cached = false; // phpcs:ignore Squiz.PHP.DisallowMultipleAssignments
301    }
302
303    if (
304        ( defined( 'WP_CLI' ) && WP_CLI ) ||
305        ( defined( 'WP_IMPORTING' ) && WP_IMPORTING )
306    ) {
307        // WP-CLI & Importers are always allowed.
308        return $cached = false; // phpcs:ignore Squiz.PHP.DisallowMultipleAssignments
309    }
310
311    return $cached = ! is_private_blog_user(); // phpcs:ignore Squiz.PHP.DisallowMultipleAssignments
312}
313
314/**
315 * Adds custom XML-RPC endpoints for private-site.
316 *
317 * @param array $methods A list of registered XML-RPC methods.
318 *
319 * @return array
320 */
321function register_additional_jetpack_xmlrpc_methods( $methods ) {
322    return array_merge(
323        $methods,
324        array(
325            'jetpack.getClosestThumbnailSizeUrl' => '\Private_Site\get_closest_thumbnail_size_url',
326            'jetpack.getReadAccessCookies'       => '\Private_Site\get_read_access_cookies',
327        )
328    );
329}
330
331/**
332 * Returns the closest thumbnail size URL.
333 *
334 * @param array $args Image arguments.
335 *
336 * @return array|false
337 */
338function get_closest_thumbnail_size_url( $args ) {
339    if ( ! isset( $args['url'] ) || ! isset( $args['width'] ) || ! isset( $args['height'] ) ) {
340        return false;
341    }
342
343    $id = attachment_url_to_postid( $args['url'] );
344    if ( ! $id ) {
345        return false;
346    }
347
348    $result = wp_get_attachment_image_src( $id, array( $args['width'], $args['height'] ) );
349    if ( ! $result ) {
350        return false;
351    }
352
353    return $result;
354}
355
356/**
357 * We use this XMLPC method to ensure wp.com is able to fetch read access cookies even
358 * when Jetpack SSO module is disabled.
359 *
360 * @param array $args Cookie args.
361 *
362 * @return array|WP_Error
363 */
364function get_read_access_cookies( $args ) {
365    $user = get_user_by( 'id', intval( $args[0] ) );
366    if ( ! $user ) {
367        return new WP_Error(
368            'account_not_found',
369            'Account not found. If you already have an account, make sure you have connected to WordPress.com.'
370        );
371    }
372    if ( ! $user->has_cap( 'read' ) ) {
373        return new WP_Error( 'access error', 'User does not have "read" capabilities' );
374    }
375
376    add_filter( 'send_auth_cookies', '__return_false' );
377    add_filter(
378        'auth_cookie_expiration',
379        function () use ( $args ) {
380            return $args[1];
381        },
382        1000
383    );
384
385    $logged_in_cookie            = null;
386    $logged_in_cookie_expiration = null;
387
388    add_action(
389        'set_logged_in_cookie',
390        function ( $_cookie, $_expires, $_expiration ) use ( &$logged_in_cookie, &$logged_in_cookie_expiration ) {
391            $logged_in_cookie            = $_cookie;
392            $logged_in_cookie_expiration = $_expiration;
393        },
394        10,
395        3
396    );
397    wp_set_auth_cookie( $user->ID, true );
398    if ( ! $logged_in_cookie ) {
399        return new WP_Error( 'authorization_failed', 'Authorization cookie was not found' );
400    }
401
402    return array(
403        array( LOGGED_IN_COOKIE, $logged_in_cookie, $logged_in_cookie_expiration ),
404    );
405}
406
407/**
408 * Checks if current request is a request sent to admin-ajax.php and initiated by remote
409 * Jetpack API.
410 *
411 * @return bool
412 */
413function is_jetpack_admin_ajax_request() {
414    // phpcs:disable WordPress.Security
415    return (
416        isset( $_SERVER['REQUEST_URI'] ) &&
417        substr( $_SERVER['REQUEST_URI'], 0, 24 ) === '/wp-admin/admin-ajax.php' &&
418        isset( $_SERVER['HTTP_AUTHORIZATION'] ) &&
419        substr( $_SERVER['HTTP_AUTHORIZATION'], 0, 9 ) === 'X_JETPACK' &&
420        array_key_exists( 'action', $_POST ) &&
421        substr( $_POST['action'], 0, 8 ) === 'jetpack_'
422    );
423    // phpcs:enable
424}
425
426/**
427 * Tell the client that the site is private and they do not have access.
428 * This function always exits PHP (`wp_send_json_error` calls `wp_die` / `die`)
429 *
430 * @return never
431 */
432function send_access_denied_error_response() {
433    global $wp;
434
435    if ( ( defined( 'DOING_AJAX' ) && DOING_AJAX ) || 'admin-ajax.php' === ( $wp->query_vars['pagename'] ?? '' ) ) {
436        wp_send_json_error(
437            array(
438                'code'    => 'private_site',
439                'message' => __(
440                    'This site is private.',
441                    'wpcomsh'
442                ),
443            ),
444            null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
445            JSON_UNESCAPED_SLASHES
446        );
447    }
448
449    require access_denied_template_path();
450    exit( 0 );
451}
452
453/**
454 * Prints robots.txt and prevents access if necessary.
455 */
456function parse_request() {
457    if ( maybe_print_robots_txt() ) {
458        // If robots.txt was requested, go ahead & serve our hard-coded version & bail
459        exit( 0 );
460    }
461
462    if ( should_prevent_site_access() ) {
463        send_access_denied_error_response();
464    }
465}
466
467/**
468 * Returns the original request URL.
469 *
470 * @return string
471 */
472function original_request_url() {
473    // phpcs:disable WordPress.Security
474    $origin = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['SERVER_NAME'];
475
476    if ( ! empty( $_SERVER['SERVER_PORT'] ) && ! in_array( $_SERVER['SERVER_PORT'], array( 80, 443 ) ) ) { //phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
477        $origin .= ':' . $_SERVER['SERVER_PORT'];
478    }
479
480    return $origin . strtok( $_SERVER['REQUEST_URI'], '?' );
481    // phpcs:enable
482}
483
484/**
485 * Hooked into `rest_api_update_site_settings` filter.
486 *
487 * This filter updates the cached value of `wpcom_coming_soon` or `launch-status`
488 * whenever `wpcom_coming_soon` option is changed on WP.com and this plugin
489 * is notified via Jetpack-WPCOM REST API bridge.
490 *
491 * @param array $input            Filtered POST input.
492 * @param array $unfiltered_input Raw and unfiltered POST input.
493 *
494 * @return array
495 */
496function cache_option_on_update_site_settings( $input, $unfiltered_input ) {
497    if ( array_key_exists( 'wpcom_coming_soon', $unfiltered_input ) ) {
498        wp_cache_set( 'wpcom_coming_soon', $unfiltered_input['wpcom_coming_soon'], 'wpcomsh' );
499    }
500
501    if ( array_key_exists( 'launch-status', $unfiltered_input ) ) {
502        wp_cache_set( 'wpcom_launch_status', $unfiltered_input['launch-status'], 'wpcomsh' );
503    }
504
505    return $input;
506}
507
508/**
509 * Requests for the "Robots" file are not blocked by the site being marked as private.
510 * If the client has requested the `/robots.txt` file, execute the `do_robots` action and return true.
511 * This function compares the request to the site_url() so it also supports subdomain installs.
512 *
513 * @see `private_robots_txt`
514 * @return bool
515 */
516function maybe_print_robots_txt() {
517    if ( untrailingslashit( original_request_url() ) === site_url( '/robots.txt' ) ) {
518        do_action( 'do_robots' );
519        return true;
520    }
521
522    return false;
523}
524
525/**
526 * Scrutinize REST API Requests _after_ the permissions checks have been applied
527 * This enforces nonce & token checking on content endpoints to prevent CSRF-style attacks
528 * If using cookie auth, clients must send a valid nonce in order to access content endpoints
529 *
530 * @see rest_dispatch_request https://core.trac.wordpress.org/browser/tags/5.2.3/src/wp-includes/rest-api/class-wp-rest-server.php#L940
531 *
532 * @param mixed           $dispatch_result Dispatch result, will be used if not empty.
533 * @param WP_REST_Request $request         Request used to generate the response.
534 * @param string          $route           Route matched for the request.
535 *
536 * @return WP_Error|null  WP_Error on disallowed, null on ok
537 */
538function rest_dispatch_request( $dispatch_result, $request, $route ) {
539    // Don't clobber other plugins.
540    if ( $dispatch_result !== null ) {
541        return $dispatch_result;
542    }
543
544    /*
545     * Allow certain endpoints for plugin-based authentication methods.
546     * These are "anchored" on the left side with `^/`, but not the right, so include the trailing `/`
547     */
548    $allowed_routes = array(
549        '2fa/', // https://wordpress.org/plugins/application-passwords/
550        'jwt-auth/', // https://wordpress.org/plugins/jwt-authentication-for-wp-rest-api/
551        'oauth1/', // https://wordpress.org/plugins/rest-api-oauth1/
552    );
553
554    if ( preg_match( '#^/(' . implode( '|', $allowed_routes ) . ')#', $route ) ) {
555        return null;
556    }
557
558    if ( should_prevent_site_access() ) {
559        return new WP_Error( 'private_site', __( 'This site is private.', 'wpcomsh' ), array( 'status' => 403 ) );
560    }
561
562    return null;
563}
564
565/**
566 * Limits XML-RPC endpoints to the ones that are allowed.
567 *
568 * @param array $methods List of XML-RPC methods.
569 *
570 * @return array
571 */
572function xmlrpc_methods_limit_to_allowed_list( $methods ) {
573    if ( should_prevent_site_access() ) {
574        return array_filter(
575            $methods,
576            function ( $key ) {
577                // Permits the Jetpack debug tool. @see p58i-8OX-p2#comment-46085.
578                return 'demo.sayHello' === $key || preg_match( '/^jetpack\..+/', $key );
579            },
580            ARRAY_FILTER_USE_KEY
581        );
582    }
583
584    return $methods;
585}
586
587/**
588 * Checks if the current user is a member of the current site.
589 *
590 * @return bool
591 */
592function is_private_blog_user() {
593    return blog_user_can();
594}
595
596/**
597 * Checks the current user's capabilities for the current site.
598 *
599 * Does not check whether the blog is private. Works on current blog & user.
600 * Returns true for super admins.
601 *
602 * @param string $capability Capability name.
603 * @return bool
604 */
605function blog_user_can( $capability = 'read' ) {
606    $user = wp_get_current_user();
607    if ( ! $user->ID ) {
608        return false;
609    }
610
611    $blog_id = get_current_blog_id();
612    if ( ! $blog_id ) {
613        return false;
614    }
615
616    // Check if the user has read permissions.
617    $the_user = clone $user;
618    $the_user->for_site( $blog_id );
619    return $the_user->has_cap( $capability );
620}
621
622/**
623 * Replaces the the site's "name" & "title" values with "Private Site"
624 * Added to the `bloginfo` filter in our `init` function
625 *
626 * @param mixed $value The requested non-URL site information.
627 * @param mixed $what  Type of information requested.
628 * @return string The potentially modified bloginfo value
629 */
630function mask_site_name( $value, $what ) {
631    if ( ! site_is_coming_soon() && should_prevent_site_access() && in_array( $what, array( 'name', 'title' ), true ) ) {
632        return __( 'Private Site', 'wpcomsh' );
633    }
634
635    return $value;
636}
637
638/**
639 * Remove the mask_site_name filter.
640 */
641function remove_mask_site_name_filter() {
642    remove_filter( 'bloginfo', '\Private_Site\mask_site_name' );
643}
644
645/**
646 * Filters new comments so that users can't comment on private blogs.
647 *
648 * @param array $comment Documented in wp-includes/comment.php.
649 *
650 * @return array
651 */
652function preprocess_comment( $comment ) {
653    if ( should_prevent_site_access() ) {
654        require access_denied_template_path();
655        exit( 0 );
656    }
657    return $comment;
658}
659
660/**
661 * Whether the current site is connected to Jetpack.
662 *
663 * @return bool
664 */
665function is_jetpack_connected() {
666    return class_exists( 'Jetpack' ) && Jetpack::is_connection_ready();
667}
668
669/**
670 * Whether we're in preview mode.
671 *
672 * @return bool
673 */
674function is_site_preview() {
675    return site_preview_source() !== false;
676}
677
678/**
679 * Returns the site preview source.
680 *
681 * @return false|string
682 */
683function site_preview_source() {
684    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- This request doesn't change any data.
685    $ua                = isset( $_SERVER['HTTP_USER_AGENT'] )
686            ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) )
687            : '';
688    $apps_ua_fragments = array(
689        'iphone-app'  => ' wp-iphone/',
690        'android-app' => ' wp-android/',
691        'desktop-app' => ' WordPressDesktop/',
692    );
693    foreach ( $apps_ua_fragments as $source => $fragment ) {
694        if ( strpos( $ua, $fragment ) !== false ) {
695            return $source;
696        }
697    }
698
699    if (
700        (
701            isset( $_GET['iframe'] )
702            && 'true' === $_GET['iframe']
703            && (
704                ( isset( $_GET['theme_preview'] ) && 'true' === $_GET['theme_preview'] )
705                || (
706                    isset( $_GET['preview'] )
707                    && 'true' === $_GET['preview']
708                )
709            )
710        )
711        || isset( $_GET['widgetPreview'] ) // Gutenberg < 9.2
712        || isset( $_GET['widget-preview'] ) // Gutenberg >= 9.2
713    ) {
714        return 'browser-iframe';
715    }
716
717    return false;
718    // phpcs:enable WordPress.Security.NonceVerification.Recommended
719}
720
721/**
722 * Grabs a proper access-denied template and returns its path.
723 */
724function access_denied_template_path() {
725    if ( is_site_preview() ) {
726        return __DIR__ . '/access-denied-preview-login-template.php';
727    }
728
729    /*
730     * Logged-out users coming from Calypso are likely authenticated in wordpress.com, so if we redirect them
731     * straight away to the login page, the SSO module will try to automatically log them in into the site.
732     */
733    $calypso_domains          = array(
734        'https://wordpress.com/',
735        'https://horizon.wordpress.com/',
736        'https://wpcalypso.wordpress.com/',
737        'http://calypso.localhost:3000/',
738        'http://127.0.0.1:41050/', // Desktop App.
739    );
740    $should_redirect_to_login = ( ! is_user_logged_in() ) && class_exists( 'Jetpack' ) && Jetpack::is_module_active( 'sso' ) && in_array( wp_get_referer(), $calypso_domains, true );
741    if ( $should_redirect_to_login ) {
742        wp_safe_redirect( wp_login_url( set_url_scheme( original_request_url() ) ) );
743        exit( 0 );
744    } elseif ( site_is_coming_soon() ) {
745        return __DIR__ . '/access-denied-coming-soon-template.php';
746    } else {
747        return __DIR__ . '/access-denied-private-site-template.php';
748    }
749}
750
751/**
752 * Hooked into filter: `allowed_options`.
753 *
754 * Prevents WordPress from saving blog_public option when site options are saved.
755 *
756 * This plugin disables the 'Site Visibility' selector in wp-admin and shows a link to Calypso instead. This function
757 * effectively prevents wp-admin from accidentally updating 'blog_public' option when other site options are updated.
758 *
759 * @param array $allow_list Options allow list.
760 * @return array
761 */
762function remove_privacy_option_from_whitelist( $allow_list ) {
763    $blog_public_index = array_search( 'blog_public', $allow_list['reading'], true );
764    unset( $allow_list['reading'][ $blog_public_index ] );
765
766    return $allow_list;
767}
768
769/**
770 * Makes it possible to disable WP.com customizations to 'Site Visibility' selector by attaching
771 * a 'wpcom_should_update_privacy_selector' filter and making sure it returns false.
772 *
773 * @return bool
774 */
775function should_update_privacy_selector() {
776    return apply_filters( 'wpcom_should_update_privacy_selector', true );
777}
778
779/**
780 * Don't let search engines index private sites.
781 * If the site is not private, do nothing.
782 *
783 * @return string The Robots.txt information.
784 */
785function private_robots_txt() {
786    // Purposefully overriding current output; we only want these rules.
787    return "User-agent: *\nDisallow: /\n";
788}
789
790// Dummy gettext calls to get strings in the catalog.
791/* translators: User role. */
792_x( 'Viewer', 'User role', 'wpcomsh' );
793
794/**
795 * Renames the "Subscriber" role to "Viewer".
796 *
797 * @param \WP_Roles $roles WP_Roles object.
798 */
799function rename_subscriber_role_to_viewer( $roles ) {
800    if ( site_is_private() && isset( $roles->roles['subscriber'] ) ) {
801        $roles->roles['subscriber']['name'] = 'Viewer';
802        $roles->role_names['subscriber']    = 'Viewer';
803    }
804}
805add_action( 'wp_roles_init', '\Private_Site\rename_subscriber_role_to_viewer' );
806
807/**
808 * Translate Viewer role using the wpcomsh textdomain.
809 *
810 * @param string $translation  Translated text.
811 * @param string $text         Text to translate.
812 * @param string $context      Context information for the translators.
813 * @param string $domain       Text domain. Unique identifier for retrieving translated strings.
814 * @return string
815 */
816function translate_viewer_role( $translation, $text, $context, $domain ) {
817    if ( 'User role' === $context && 'default' === $domain && 'Viewer' === $text ) {
818        return translate_user_role( $text, 'wpcomsh' );
819    }
820
821    return $translation;
822}
823add_filter( 'gettext_with_context', '\Private_Site\translate_viewer_role', 10, 4 );
824
825/**
826 * Output the meta tag that tells Pinterest not to allow users to pin
827 * content from this page.
828 * https://support.pinterest.com/entries/21063792-what-if-i-don-t-want-images-from-my-site-to-be-pinned
829 */
830function private_no_pinning() {
831    echo '<meta name="pinterest" content="nopin" />';
832}
833
834/**
835 * Returns the private page template for OPML.
836 */
837function hide_opml() {
838    if ( should_prevent_site_access() ) {
839        status_header( 403 );
840        ?>
841        <error><?php esc_html_e( 'This site is private.', 'wpcomsh' ); ?></error>
842    </head>
843</opml>
844        <?php
845        exit( 0 );
846    }
847}
848
849/**
850 * Removes disabled modules from the active list for private sites.
851 *
852 * @param array $modules Active modules.
853 *
854 * @return array Array of modules after filtering.
855 */
856function filter_jetpack_active_modules( $modules ) {
857    return array_filter(
858        $modules,
859        function ( $module_name ) {
860            return ! in_array( $module_name, DISABLED_JETPACK_MODULES_WHEN_PRIVATE, true );
861        }
862    );
863}
864
865/**
866 * Disables modules for private sites.
867 *
868 * @param array $modules Available modules.
869 *
870 * @return array Array of modules after filtering.
871 */
872function filter_jetpack_get_available_modules( $modules ) {
873    return array_filter(
874        $modules,
875        function ( $module_name ) {
876            return ! in_array( $module_name, DISABLED_JETPACK_MODULES_WHEN_PRIVATE, true );
877        },
878        ARRAY_FILTER_USE_KEY
879    );
880}
881
882/**
883 * Classic editor in calypso don't support displaying private media files because of CORS issues. Adding
884 * a support would be super complex and probably not worth it, considering that we're phasing out the classical
885 * editor altogether. Classic editor in wp-admin handles private files out of the box so we're redirecting all
886 * private+atomic+classic editor users from calypso to wp-admin with ?classic_editor.
887 *
888 * This hook ensures that all requests to post.php and post-new.php will show classic editor when ?classic_editor query
889 * parameter is present.
890 */
891function use_classic_editor_if_requested() {
892    if ( ! is_module_active() ) {
893        return;
894    }
895
896    if ( ! should_override_editor_with_classic_editor() ) {
897        return;
898    }
899
900    if ( class_exists( '\Classic_Editor' ) ) {
901        // This should never happen since we disabled the plugin in another filter
902        return;
903    }
904
905    add_action(
906        'classic_editor_plugin_settings',
907        function () {
908            return array(
909                'editor'      => 'classic',
910                'allow-users' => false,
911            );
912        }
913    );
914
915    require dirname( __DIR__ ) . '/vendor/wordpress/classic-editor-plugin/classic-editor.php';
916    \Classic_Editor::init_actions();
917
918    /*
919     * Classic editor registers itself to plugins_loaded action.
920     * By now it was already executed, but let's remove it just to be safe.
921     */
922    remove_action( 'plugins_loaded', array( 'Classic_Editor', 'init_actions' ) );
923
924    // In allow-users => false mode, these redirection helpers aren't used. Let's apply them manually.
925    add_filter( 'get_edit_post_link', array( 'Classic_Editor', 'get_edit_post_link' ) );
926    add_filter( 'redirect_post_location', array( 'Classic_Editor', 'redirect_location' ) );
927    add_action( 'edit_form_top', array( 'Classic_Editor', 'add_redirect_helper' ) );
928    add_action( 'admin_head-edit.php', array( 'Classic_Editor', 'add_edit_php_inline_style' ) );
929
930    /*
931     * Let's disable Calypsoify - it gets triggered when the user:
932     * 1. Opens Gutenberg.
933     * 2. Clicks "Switch to classic editor".
934     * 3. Clicks "Use Classic editor" in the prompt.
935     */
936    add_filter(
937        'get_user_metadata',
938        function ( $value, $object_id, $meta_key ) {
939            if ( $meta_key === 'calypsoify' ) {
940                return 0;
941            }
942
943            return $value;
944        },
945        10,
946        3
947    );
948}
949
950/**
951 * Disables the classic editor plugin when active.
952 *
953 * @param array $plugins List of active plugins.
954 *
955 * @return array
956 */
957function disable_classic_editor_plugin_when_needed( $plugins ) {
958    if ( ! is_module_active() ) {
959        return $plugins;
960    }
961
962    if ( ! should_override_editor_with_classic_editor() ) {
963        return $plugins;
964    }
965
966    $key = array_search( 'classic-editor/classic-editor.php', $plugins, true );
967    if ( false !== $key ) {
968        unset( $plugins[ $key ] );
969    }
970
971    return $plugins;
972}
973add_filter( 'option_active_plugins', '\Private_Site\disable_classic_editor_plugin_when_needed', 1000 );
974
975/**
976 * Determines whether to override the editor with the Classic Editor.
977 *
978 * @return bool
979 */
980function should_override_editor_with_classic_editor() {
981    if ( ! site_is_private() ) {
982        return false;
983    }
984
985    global $pagenow;
986    if ( empty( $pagenow ) ) {
987        return false;
988    }
989
990    if ( $pagenow !== 'post.php' && $pagenow !== 'post-new.php' ) {
991        return false;
992    }
993
994    if ( ! array_key_exists( 'classic-editor', $_REQUEST ) ) { // phpcs:ignore WordPress.Security.NonceVerification
995        return false;
996    }
997
998    if ( array_key_exists( 'classic-editor__forget', $_REQUEST ) ) {  // phpcs:ignore WordPress.Security.NonceVerification
999        return false;
1000    }
1001
1002    return true;
1003}