Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
22.92% covered (danger)
22.92%
22 / 96
22.22% covered (danger)
22.22%
2 / 9
CRAP
n/a
0 / 0
wpcomsh_upgrade_transferred_db
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
240
wpcomsh_wp_die_handler
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
wpcomsh_get_wp_die_handler
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wpcomsh_maybe_enable_link_manager
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
wpcomsh_limit_post_revisions
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
wpcomsh_site_status_tests_disable
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
wpcomsh_prevent_owner_removal
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
6
wpcomsh_get_connection_owner_id
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
8.04
wpcomsh_reset_connection_owner_id
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * File for all Atomic-specific changes to WordPress.
4 *
5 * @package wpcomsh
6 */
7
8/**
9 * Upgrade transferred db.
10 *
11 * @return void
12 */
13function wpcomsh_upgrade_transferred_db() {
14    global $wp_db_version;
15
16    if ( isset( $_SERVER['ATOMIC_SITE_ID'] ) ) {
17        $atomic_site_id = $_SERVER['ATOMIC_SITE_ID']; //phpcs:ignore WordPress.Security.ValidatedSanitizedInput
18    } elseif ( defined( 'ATOMIC_SITE_ID' ) ) {
19        $atomic_site_id = ATOMIC_SITE_ID;
20    }
21
22    if (
23        empty( $atomic_site_id ) ||
24        $atomic_site_id <= 149474462 /* Last site ID before WP 5.5 update. */
25    ) {
26        // We only want to run for real sites created after the WordPress 5.5 update.
27        return;
28    }
29
30    // Value taken from https://github.com/WordPress/wordpress-develop/blob/b591209e141e0357a69fff1d01d2650ac2d916cb/src/wp-includes/version.php#L23
31    $db_version_5_5 = 48748;
32
33    if ( $wp_db_version < $db_version_5_5 ) {
34        // WordPress isn't yet at the version for upgrade.
35        return;
36    }
37
38    if ( get_option( 'wpcomsh_upgraded_db' ) ) {
39        /*
40         * We only ever want to upgrade the DB once per transferred site.
41         * After that, the platform should take care of upgrades as WordPress is updated.
42         */
43        return;
44    }
45
46    /*
47     * Log the upgrade immediately because we do not want to re-attempt upgrade and bring down a site if there are
48     * persistent errors.
49     */
50    update_option( 'wpcomsh_upgraded_db', 1 );
51
52    /*
53     * We have to be in installation mode to work with options deprecated in WP 5.5.
54     * Otherwise all gets and updates are directed to the new option names.
55     */
56    wp_installing( true );
57
58    // Logic derived from: https://github.com/WordPress/wordpress-develop/blob/b591209e141e0357a69fff1d01d2650ac2d916cb/src/wp-admin/includes/upgrade.php#L2176
59    if (
60        false !== get_option( 'comment_whitelist' ) && // phpcs:ignore WordPress.WP.DeprecatedParameterValues.Found
61        // Default value from: https://github.com/WordPress/wordpress-develop/blob/f0733600c9b8a0833d7e63f60fae651d46f22320/src/wp-admin/includes/schema.php#L536
62        in_array( get_option( 'comment_previously_approved' ), array( false, 1 /* default value */ ) ) //phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
63    ) {
64        $comment_previously_approved = get_option( 'comment_whitelist', '' ); // phpcs:ignore WordPress.WP.DeprecatedParameterValues.Found
65        update_option( 'comment_previously_approved', $comment_previously_approved );
66        delete_option( 'comment_whitelist' );
67    }
68
69    // Logic derived from: https://github.com/WordPress/wordpress-develop/blob/b591209e141e0357a69fff1d01d2650ac2d916cb/src/wp-admin/includes/upgrade.php#L2182
70    if (
71        false !== get_option( 'blacklist_keys' ) && // phpcs:ignore WordPress.WP.DeprecatedParameterValues.Found
72        // Default value from https://github.com/WordPress/wordpress-develop/blob/f0733600c9b8a0833d7e63f60fae651d46f22320/src/wp-admin/includes/schema.php#L535
73        in_array( get_option( 'disallowed_keys' ), array( false, '' /* default value */ ) ) //phpcs:ignore WordPress.PHP.StrictInArray.MissingTrueStrict
74    ) {
75        // Use more clear and inclusive language.
76        $disallowed_list = get_option( 'blacklist_keys' ); // phpcs:ignore WordPress.WP.DeprecatedParameterValues.Found
77
78        /*
79         * This option key was briefly renamed `blocklist_keys`.
80         * Account for sites that have this key present when the original key does not exist.
81         */
82        if ( false === $disallowed_list ) {
83            $disallowed_list = get_option( 'blocklist_keys' );
84        }
85
86        update_option( 'disallowed_keys', $disallowed_list );
87        delete_option( 'blacklist_keys' );
88        delete_option( 'blocklist_keys' );
89    }
90
91    // We're done updating deprecated options.
92    wp_installing( false );
93
94    /*
95     * Make sure that comment_type update is attempted.
96     *
97     * @see https://github.com/WordPress/wordpress-develop/blob/b591209e141e0357a69fff1d01d2650ac2d916cb/src/wp-admin/includes/upgrade.php#L2199
98     */
99    if (
100        ! get_option( 'finished_updating_comment_type' ) &&
101        false === wp_next_scheduled( 'wp_update_comment_type_batch' )
102    ) {
103        update_option( 'finished_updating_comment_type', 0 );
104        wp_schedule_single_event( time() + ( 1 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
105    }
106
107    // We need to be in installation mode to get actual, saved DB version.
108    wp_installing( true );
109    $current_db_version = get_option( 'db_version' );
110    wp_installing( false );
111
112    /*
113     * Update DB version to avoid applying core upgrade logic which may be destructive
114     * to things like the new `comment_previously_approved` option.
115     *
116     * @see https://github.com/WordPress/wordpress-develop/blob/b591209e141e0357a69fff1d01d2650ac2d916cb/src/wp-admin/includes/upgrade.php#L2178
117     */
118    if ( $current_db_version < $db_version_5_5 ) {
119        update_option( 'db_version', $db_version_5_5 );
120
121        // Preserve previous version for troubleshooting.
122        update_option( 'wpcom_db_version_before_upgrade', $current_db_version, false /* Do not autoload. */ );
123    }
124}
125add_action( 'muplugins_loaded', 'wpcomsh_upgrade_transferred_db' );
126
127/**
128 * Logs wp_die() calls.
129 *
130 * @param string|WP_Error $message Error message or WP_Error object.
131 * @param string          $title   Optional. Error title. Default empty.
132 * @param string|array    $args    Optional. Arguments to control behavior. Default empty array.
133 * @return void
134 */
135function wpcomsh_wp_die_handler( $message, $title = '', $args = array() ) {
136    $exception = new Exception( 'wp_die was called' );
137    error_log( $exception ); //phpcs:ignore WordPress.PHP.DevelopmentFunctions
138
139    if ( function_exists( '_default_wp_die_handler' ) ) {
140        _default_wp_die_handler( $message, $title, $args );
141        return;
142    }
143
144    // If the default wp_die handler is not available just die.
145    die( 0 );
146}
147
148/**
149 * Get wp die handler.
150 */
151function wpcomsh_get_wp_die_handler() {
152    return 'wpcomsh_wp_die_handler';
153}
154// Disabling the die handler per p9F6qB-3TQ-p2
155// add_filter( 'wp_die_handler', 'wpcomsh_get_wp_die_handler' );
156
157/**
158 * Links were removed in 3.5 core, but we've kept them active on dotcom.
159 *
160 * This function will check to see if links should be enabled based on the number of links in the database
161 * and then set an option to minimize repeat queries later.
162 *
163 * @return void
164 */
165function wpcomsh_maybe_enable_link_manager() {
166    if ( get_option( 'link_manager_check' ) ) {
167        return;
168    }
169
170    // The max ID number of the auto-generated links.
171    // See /wp-content/mu-plugins/wpcom-wp-install-defaults.php in WP.com.
172    $max_default_id = 10;
173
174    // We are only checking the latest entry link_id so are limiting the query to 1.
175    $link_manager_links = get_bookmarks(
176        array(
177            'orderby'        => 'link_id',
178            'order'          => 'DESC',
179            'limit'          => 1,
180            'hide_invisible' => 0,
181        )
182    );
183
184    $has_links = is_countable( $link_manager_links ) && count( $link_manager_links ) > 0 && $link_manager_links[0]->link_id > $max_default_id;
185
186    update_option( 'link_manager_enabled', intval( $has_links ) );
187    update_option( 'link_manager_check', time() );
188}
189add_action( 'init', 'wpcomsh_maybe_enable_link_manager' );
190
191/**
192 * WordPress 5.3 adds "big image" processing, for images over 2560px (by default).
193 * This is not needed on Atomic since we use Photon for dynamic image work.
194 */
195add_filter( 'big_image_size_threshold', '__return_false' );
196
197/**
198 * WordPress 5.3 adds periodic admin email verification, disable it for WordPress.com on Atomic.
199 */
200add_filter( 'admin_email_check_interval', '__return_zero' );
201
202/**
203 * Limit post revisions.
204 *
205 * @return int
206 */
207function wpcomsh_limit_post_revisions() {
208    return 100;
209}
210add_filter( 'wp_revisions_to_keep', 'wpcomsh_limit_post_revisions', 5 );
211
212/**
213 * Remove WordPress 5.2+ Site Health Tests that are not a good fit for Atomic.
214 *
215 * @param array $tests An associative array to declare if the test should run via Ajax calls after page load.
216 * @return array
217 */
218function wpcomsh_site_status_tests_disable( $tests ) {
219    unset( $tests['direct']['plugin_version'] );
220    unset( $tests['direct']['theme_version'] );
221
222    return $tests;
223}
224add_filter( 'site_status_tests', 'wpcomsh_site_status_tests_disable' );
225
226/**
227 * Don't allow site owners to be removed.
228 *
229 * @param array $allcaps An array of all the user's capabilities.
230 * @param array $caps    Actual capabilities for meta capability.
231 * @param array $args    Optional parameters passed to has_cap(), typically object ID.
232 * @return array
233 */
234function wpcomsh_prevent_owner_removal( $allcaps, $caps, $args ) {
235    // Trying to edit or delete a user other than yourself?
236    if ( ! isset( $args[2] ) || ! in_array( $args[0], array( 'edit_user', 'delete_user', 'remove_user', 'promote_user' ), true ) ) {
237        return $allcaps;
238    }
239
240    // Protect the owner in external storage and the owner in the row, so the guard fails closed when they differ.
241    $jetpack   = get_option( 'jetpack_options' );
242    $owner_ids = array(
243        wpcomsh_get_connection_owner_id(),
244        is_array( $jetpack ) && isset( $jetpack['master_user'] ) ? (int) $jetpack['master_user'] : 0,
245    );
246
247    if ( in_array( (int) $args[2], array_filter( $owner_ids ), true ) ) {
248        return array();
249    }
250
251    return $allcaps;
252}
253add_filter( 'user_has_cap', 'wpcomsh_prevent_owner_removal', 10, 3 );
254
255/**
256 * Returns the connection owner's user ID through `Jetpack_Options`, which reads external storage first.
257 *
258 * On Atomic, external storage names the local user who has the owner's email, and a user can set their
259 * own email. So the owner counts only when they are an administrator.
260 *
261 * The value is cached for the request: on Atomic, a missing owner costs an uncached email lookup on each call.
262 *
263 * @param bool $reset Whether to clear the cached value.
264 * @return int The user ID, or 0.
265 */
266function wpcomsh_get_connection_owner_id( $reset = false ) {
267    static $owner_id = null;
268
269    if ( $reset ) {
270        $owner_id = null;
271        return 0;
272    }
273
274    if ( null !== $owner_id ) {
275        return $owner_id;
276    }
277
278    // Before pluggable.php loads, the owner cannot be looked up, so do not cache that result.
279    if ( ! function_exists( 'get_userdata' ) ) {
280        return 0;
281    }
282
283    $user_id = class_exists( 'Jetpack_Options' ) ? (int) Jetpack_Options::get_option( 'master_user' ) : 0;
284    // Read the roles directly: user_can() would run this capability filter again.
285    $user     = $user_id ? get_userdata( $user_id ) : false;
286    $owner_id = $user && in_array( 'administrator', (array) $user->roles, true ) ? $user_id : 0;
287
288    return $owner_id;
289}
290
291/**
292 * Clears the cached connection owner when the owner's storage or the users change.
293 */
294function wpcomsh_reset_connection_owner_id() {
295    wpcomsh_get_connection_owner_id( true );
296}
297foreach ( array( 'jetpack_external_storage_provider_registered', 'add_option_jetpack_options', 'update_option_jetpack_options', 'delete_option_jetpack_options', 'user_register', 'profile_update', 'set_user_role', 'deleted_user' ) as $wpcomsh_owner_reset_hook ) {
298    add_action( $wpcomsh_owner_reset_hook, 'wpcomsh_reset_connection_owner_id' );
299}
300unset( $wpcomsh_owner_reset_hook );