Make WordPress Core

Ticket #58221: class-wp-site-health.php

File class-wp-site-health.php, 111.7 KB (added by toddlahman, 3 years ago)

File with corrections.

Line 
1<?php
2/**
3 * Class for looking up a site's health based on a user's WordPress environment.
4 *
5 * @package WordPress
6 * @subpackage Site_Health
7 * @since 5.2.0
8 */
9
10#[AllowDynamicProperties]
11class WP_Site_Health {
12        private static $instance = null;
13
14        private $is_acceptable_mysql_version;
15        private $is_recommended_mysql_version;
16
17        public $is_mariadb                   = false;
18        private $mysql_server_version        = '';
19        private $mysql_required_version      = '5.5';
20        private $mysql_recommended_version   = '5.7';
21        private $mariadb_recommended_version = '10.4';
22
23        public $php_memory_limit;
24
25        public $schedules;
26        public $crons;
27        public $last_missed_cron     = null;
28        public $last_late_cron       = null;
29        private $timeout_missed_cron = null;
30        private $timeout_late_cron   = null;
31
32        /**
33         * WP_Site_Health constructor.
34         *
35         * @since 5.2.0
36         */
37        public function __construct() {
38                $this->maybe_create_scheduled_event();
39
40                // Save memory limit before it's affected by wp_raise_memory_limit( 'admin' ).
41                $this->php_memory_limit = ini_get( 'memory_limit' );
42
43                $this->timeout_late_cron   = 0;
44                $this->timeout_missed_cron = - 5 * MINUTE_IN_SECONDS;
45
46                if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) {
47                        $this->timeout_late_cron   = - 15 * MINUTE_IN_SECONDS;
48                        $this->timeout_missed_cron = - 1 * HOUR_IN_SECONDS;
49                }
50
51                add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
52
53                add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
54                add_action( 'wp_site_health_scheduled_check', array( $this, 'wp_cron_scheduled_check' ) );
55
56                add_action( 'site_health_tab_content', array( $this, 'show_site_health_tab' ) );
57        }
58
59        /**
60         * Outputs the content of a tab in the Site Health screen.
61         *
62         * @since 5.8.0
63         *
64         * @param string $tab Slug of the current tab being displayed.
65         */
66        public function show_site_health_tab( $tab ) {
67                if ( 'debug' === $tab ) {
68                        require_once ABSPATH . 'wp-admin/site-health-info.php';
69                }
70        }
71
72        /**
73         * Returns an instance of the WP_Site_Health class, or create one if none exist yet.
74         *
75         * @since 5.4.0
76         *
77         * @return WP_Site_Health|null
78         */
79        public static function get_instance() {
80                if ( null === self::$instance ) {
81                        self::$instance = new WP_Site_Health();
82                }
83
84                return self::$instance;
85        }
86
87        /**
88         * Enqueues the site health scripts.
89         *
90         * @since 5.2.0
91         */
92        public function enqueue_scripts() {
93                $screen = get_current_screen();
94                if ( 'site-health' !== $screen->id && 'dashboard' !== $screen->id ) {
95                        return;
96                }
97
98                $health_check_js_variables = array(
99                        'screen'      => $screen->id,
100                        'nonce'       => array(
101                                'site_status'        => wp_create_nonce( 'health-check-site-status' ),
102                                'site_status_result' => wp_create_nonce( 'health-check-site-status-result' ),
103                        ),
104                        'site_status' => array(
105                                'direct' => array(),
106                                'async'  => array(),
107                                'issues' => array(
108                                        'good'        => 0,
109                                        'recommended' => 0,
110                                        'critical'    => 0,
111                                ),
112                        ),
113                );
114
115                $issue_counts = get_transient( 'health-check-site-status-result' );
116
117                if ( false !== $issue_counts ) {
118                        $issue_counts = json_decode( $issue_counts );
119
120                        $health_check_js_variables['site_status']['issues'] = $issue_counts;
121                }
122
123                if ( 'site-health' === $screen->id && ( ! isset( $_GET['tab'] ) || empty( $_GET['tab'] ) ) ) {
124                        $tests = WP_Site_Health::get_tests();
125
126                        // Don't run https test on development environments.
127                        if ( $this->is_development_environment() ) {
128                                unset( $tests['async']['https_status'] );
129                        }
130
131                        foreach ( $tests['direct'] as $test ) {
132                                if ( is_string( $test['test'] ) ) {
133                                        $test_function = sprintf(
134                                                'get_test_%s',
135                                                $test['test']
136                                        );
137
138                                        if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
139                                                $health_check_js_variables['site_status']['direct'][] = $this->perform_test( array( $this, $test_function ) );
140                                                continue;
141                                        }
142                                }
143
144                                if ( is_callable( $test['test'] ) ) {
145                                        $health_check_js_variables['site_status']['direct'][] = $this->perform_test( $test['test'] );
146                                }
147                        }
148
149                        foreach ( $tests['async'] as $test ) {
150                                if ( is_string( $test['test'] ) ) {
151                                        $health_check_js_variables['site_status']['async'][] = array(
152                                                'test'      => $test['test'],
153                                                'has_rest'  => ( isset( $test['has_rest'] ) ? $test['has_rest'] : false ),
154                                                'completed' => false,
155                                                'headers'   => isset( $test['headers'] ) ? $test['headers'] : array(),
156                                        );
157                                }
158                        }
159                }
160
161                wp_localize_script( 'site-health', 'SiteHealth', $health_check_js_variables );
162        }
163
164        /**
165         * Runs a Site Health test directly.
166         *
167         * @since 5.4.0
168         *
169         * @param callable $callback
170         * @return mixed|void
171         */
172        private function perform_test( $callback ) {
173                /**
174                 * Filters the output of a finished Site Health test.
175                 *
176                 * @since 5.3.0
177                 *
178                 * @param array $test_result {
179                 *     An associative array of test result data.
180                 *
181                 *     @type string $label       A label describing the test, and is used as a header in the output.
182                 *     @type string $status      The status of the test, which can be a value of `good`, `recommended` or `critical`.
183                 *     @type array  $badge {
184                 *         Tests are put into categories which have an associated badge shown, these can be modified and assigned here.
185                 *
186                 *         @type string $label The test label, for example `Performance`.
187                 *         @type string $color Default `blue`. A string representing a color to use for the label.
188                 *     }
189                 *     @type string $description A more descriptive explanation of what the test looks for, and why it is important for the end user.
190                 *     @type string $actions     An action to direct the user to where they can resolve the issue, if one exists.
191                 *     @type string $test        The name of the test being ran, used as a reference point.
192                 * }
193                 */
194                return apply_filters( 'site_status_test_result', call_user_func( $callback ) );
195        }
196
197        /**
198         * Runs the SQL version checks.
199         *
200         * These values are used in later tests, but the part of preparing them is more easily managed
201         * early in the class for ease of access and discovery.
202         *
203         * @since 5.2.0
204         *
205         * @global wpdb $wpdb WordPress database abstraction object.
206         */
207        private function prepare_sql_data() {
208                global $wpdb;
209
210                $mysql_server_type = $wpdb->db_server_info();
211
212                $this->mysql_server_version = $wpdb->get_var( 'SELECT VERSION()' );
213
214                if ( stristr( $mysql_server_type, 'mariadb' ) ) {
215                        $this->is_mariadb                = true;
216                        $this->mysql_recommended_version = $this->mariadb_recommended_version;
217                }
218
219                $this->is_acceptable_mysql_version  = version_compare( $this->mysql_required_version, $this->mysql_server_version, '<=' );
220                $this->is_recommended_mysql_version = version_compare( $this->mysql_recommended_version, $this->mysql_server_version, '<=' );
221        }
222
223        /**
224         * Tests whether `wp_version_check` is blocked.
225         *
226         * It's possible to block updates with the `wp_version_check` filter, but this can't be checked
227         * during an Ajax call, as the filter is never introduced then.
228         *
229         * This filter overrides a standard page request if it's made by an admin through the Ajax call
230         * with the right query argument to check for this.
231         *
232         * @since 5.2.0
233         */
234        public function check_wp_version_check_exists() {
235                if ( ! is_admin() || ! is_user_logged_in() || ! current_user_can( 'update_core' ) || ! isset( $_GET['health-check-test-wp_version_check'] ) ) {
236                        return;
237                }
238
239                echo ( has_filter( 'wp_version_check', 'wp_version_check' ) ? 'yes' : 'no' );
240
241                die();
242        }
243
244        /**
245         * Tests for WordPress version and outputs it.
246         *
247         * Gives various results depending on what kind of updates are available, if any, to encourage
248         * the user to install security updates as a priority.
249         *
250         * @since 5.2.0
251         *
252         * @return array The test result.
253         */
254        public function get_test_wordpress_version() {
255                $result = array(
256                        'label'       => '',
257                        'status'      => '',
258                        'badge'       => array(
259                                'label' => __( 'Performance' ),
260                                'color' => 'blue',
261                        ),
262                        'description' => '',
263                        'actions'     => '',
264                        'test'        => 'wordpress_version',
265                );
266
267                $core_current_version = get_bloginfo( 'version' );
268                $core_updates         = get_core_updates();
269
270                if ( ! is_array( $core_updates ) ) {
271                        $result['status'] = 'recommended';
272
273                        $result['label'] = sprintf(
274                                /* translators: %s: Your current version of WordPress. */
275                                __( 'WordPress version %s' ),
276                                $core_current_version
277                        );
278
279                        $result['description'] = sprintf(
280                                '<p>%s</p>',
281                                __( 'Unable to check if any new versions of WordPress are available.' )
282                        );
283
284                        $result['actions'] = sprintf(
285                                '<a href="%s">%s</a>',
286                                esc_url( admin_url( 'update-core.php?force-check=1' ) ),
287                                __( 'Check for updates manually' )
288                        );
289                } else {
290                        foreach ( $core_updates as $core => $update ) {
291                                if ( 'upgrade' === $update->response ) {
292                                        $current_version = explode( '.', $core_current_version );
293                                        $new_version     = explode( '.', $update->version );
294
295                                        $current_major = $current_version[0] . '.' . $current_version[1];
296                                        $new_major     = $new_version[0] . '.' . $new_version[1];
297
298                                        $result['label'] = sprintf(
299                                                /* translators: %s: The latest version of WordPress available. */
300                                                __( 'WordPress update available (%s)' ),
301                                                $update->version
302                                        );
303
304                                        $result['actions'] = sprintf(
305                                                '<a href="%s">%s</a>',
306                                                esc_url( admin_url( 'update-core.php' ) ),
307                                                __( 'Install the latest version of WordPress' )
308                                        );
309
310                                        if ( $current_major !== $new_major ) {
311                                                // This is a major version mismatch.
312                                                $result['status']      = 'recommended';
313                                                $result['description'] = sprintf(
314                                                        '<p>%s</p>',
315                                                        __( 'A new version of WordPress is available.' )
316                                                );
317                                        } else {
318                                                // This is a minor version, sometimes considered more critical.
319                                                $result['status']         = 'critical';
320                                                $result['badge']['label'] = __( 'Security' );
321                                                $result['description']    = sprintf(
322                                                        '<p>%s</p>',
323                                                        __( 'A new minor update is available for your site. Because minor updates often address security, it&#8217;s important to install them.' )
324                                                );
325                                        }
326                                } else {
327                                        $result['status'] = 'good';
328                                        $result['label']  = sprintf(
329                                                /* translators: %s: The current version of WordPress installed on this site. */
330                                                __( 'Your version of WordPress (%s) is up to date' ),
331                                                $core_current_version
332                                        );
333
334                                        $result['description'] = sprintf(
335                                                '<p>%s</p>',
336                                                __( 'You are currently running the latest version of WordPress available, keep it up!' )
337                                        );
338                                }
339                        }
340                }
341
342                return $result;
343        }
344
345        /**
346         * Tests if plugins are outdated, or unnecessary.
347         *
348         * The test checks if your plugins are up to date, and encourages you to remove any
349         * that are not in use.
350         *
351         * @since 5.2.0
352         *
353         * @return array The test result.
354         */
355        public function get_test_plugin_version() {
356                $result = array(
357                        'label'       => __( 'Your plugins are all up to date' ),
358                        'status'      => 'good',
359                        'badge'       => array(
360                                'label' => __( 'Security' ),
361                                'color' => 'blue',
362                        ),
363                        'description' => sprintf(
364                                '<p>%s</p>',
365                                __( 'Plugins extend your site&#8217;s functionality with things like contact forms, ecommerce and much more. That means they have deep access to your site, so it&#8217;s vital to keep them up to date.' )
366                        ),
367                        'actions'     => sprintf(
368                                '<p><a href="%s">%s</a></p>',
369                                esc_url( admin_url( 'plugins.php' ) ),
370                                __( 'Manage your plugins' )
371                        ),
372                        'test'        => 'plugin_version',
373                );
374
375                $plugins        = get_plugins();
376                $plugin_updates = get_plugin_updates();
377
378                $plugins_active      = 0;
379                $plugins_total       = 0;
380                $plugins_need_update = 0;
381
382                // Loop over the available plugins and check their versions and active state.
383                foreach ( $plugins as $plugin_path => $plugin ) {
384                        $plugins_total++;
385
386                        if ( is_plugin_active( $plugin_path ) ) {
387                                $plugins_active++;
388                        }
389
390                        if ( array_key_exists( $plugin_path, $plugin_updates ) ) {
391                                $plugins_need_update++;
392                        }
393                }
394
395                // Add a notice if there are outdated plugins.
396                if ( $plugins_need_update > 0 ) {
397                        $result['status'] = 'critical';
398
399                        $result['label'] = __( 'You have plugins waiting to be updated' );
400
401                        $result['description'] .= sprintf(
402                                '<p>%s</p>',
403                                sprintf(
404                                        /* translators: %d: The number of outdated plugins. */
405                                        _n(
406                                                'Your site has %d plugin waiting to be updated.',
407                                                'Your site has %d plugins waiting to be updated.',
408                                                $plugins_need_update
409                                        ),
410                                        $plugins_need_update
411                                )
412                        );
413
414                        $result['actions'] .= sprintf(
415                                '<p><a href="%s">%s</a></p>',
416                                esc_url( network_admin_url( 'plugins.php?plugin_status=upgrade' ) ),
417                                __( 'Update your plugins' )
418                        );
419                } else {
420                        if ( 1 === $plugins_active ) {
421                                $result['description'] .= sprintf(
422                                        '<p>%s</p>',
423                                        __( 'Your site has 1 active plugin, and it is up to date.' )
424                                );
425                        } elseif ( $plugins_active > 0 ) {
426                                $result['description'] .= sprintf(
427                                        '<p>%s</p>',
428                                        sprintf(
429                                                /* translators: %d: The number of active plugins. */
430                                                _n(
431                                                        'Your site has %d active plugin, and it is up to date.',
432                                                        'Your site has %d active plugins, and they are all up to date.',
433                                                        $plugins_active
434                                                ),
435                                                $plugins_active
436                                        )
437                                );
438                        } else {
439                                $result['description'] .= sprintf(
440                                        '<p>%s</p>',
441                                        __( 'Your site does not have any active plugins.' )
442                                );
443                        }
444                }
445
446                // Check if there are inactive plugins.
447                if ( $plugins_total > $plugins_active && ! is_multisite() ) {
448                        $unused_plugins = $plugins_total - $plugins_active;
449
450                        $result['status'] = 'recommended';
451
452                        $result['label'] = __( 'You should remove inactive plugins' );
453
454                        $result['description'] .= sprintf(
455                                '<p>%s %s</p>',
456                                sprintf(
457                                        /* translators: %d: The number of inactive plugins. */
458                                        _n(
459                                                'Your site has %d inactive plugin.',
460                                                'Your site has %d inactive plugins.',
461                                                $unused_plugins
462                                        ),
463                                        $unused_plugins
464                                ),
465                                __( 'Inactive plugins are tempting targets for attackers. If you are not going to use a plugin, you should consider removing it.' )
466                        );
467
468                        $result['actions'] .= sprintf(
469                                '<p><a href="%s">%s</a></p>',
470                                esc_url( admin_url( 'plugins.php?plugin_status=inactive' ) ),
471                                __( 'Manage inactive plugins' )
472                        );
473                }
474
475                return $result;
476        }
477
478        /**
479         * Tests if themes are outdated, or unnecessary.
480         *
481         * Checks if your site has a default theme (to fall back on if there is a need),
482         * if your themes are up to date and, finally, encourages you to remove any themes
483         * that are not needed.
484         *
485         * @since 5.2.0
486         *
487         * @return array The test results.
488         */
489        public function get_test_theme_version() {
490                $result = array(
491                        'label'       => __( 'Your themes are all up to date' ),
492                        'status'      => 'good',
493                        'badge'       => array(
494                                'label' => __( 'Security' ),
495                                'color' => 'blue',
496                        ),
497                        'description' => sprintf(
498                                '<p>%s</p>',
499                                __( 'Themes add your site&#8217;s look and feel. It&#8217;s important to keep them up to date, to stay consistent with your brand and keep your site secure.' )
500                        ),
501                        'actions'     => sprintf(
502                                '<p><a href="%s">%s</a></p>',
503                                esc_url( admin_url( 'themes.php' ) ),
504                                __( 'Manage your themes' )
505                        ),
506                        'test'        => 'theme_version',
507                );
508
509                $theme_updates = get_theme_updates();
510
511                $themes_total        = 0;
512                $themes_need_updates = 0;
513                $themes_inactive     = 0;
514
515                // This value is changed during processing to determine how many themes are considered a reasonable amount.
516                $allowed_theme_count = 1;
517
518                $has_default_theme   = false;
519                $has_unused_themes   = false;
520                $show_unused_themes  = true;
521                $using_default_theme = false;
522
523                // Populate a list of all themes available in the install.
524                $all_themes   = wp_get_themes();
525                $active_theme = wp_get_theme();
526
527                // If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme.
528                $default_theme = wp_get_theme( WP_DEFAULT_THEME );
529                if ( ! $default_theme->exists() ) {
530                        $default_theme = WP_Theme::get_core_default_theme();
531                }
532
533                if ( $default_theme ) {
534                        $has_default_theme = true;
535
536                        if (
537                                $active_theme->get_stylesheet() === $default_theme->get_stylesheet()
538                        ||
539                                is_child_theme() && $active_theme->get_template() === $default_theme->get_template()
540                        ) {
541                                $using_default_theme = true;
542                        }
543                }
544
545                foreach ( $all_themes as $theme_slug => $theme ) {
546                        $themes_total++;
547
548                        if ( array_key_exists( $theme_slug, $theme_updates ) ) {
549                                $themes_need_updates++;
550                        }
551                }
552
553                // If this is a child theme, increase the allowed theme count by one, to account for the parent.
554                if ( is_child_theme() ) {
555                        $allowed_theme_count++;
556                }
557
558                // If there's a default theme installed and not in use, we count that as allowed as well.
559                if ( $has_default_theme && ! $using_default_theme ) {
560                        $allowed_theme_count++;
561                }
562
563                if ( $themes_total > $allowed_theme_count ) {
564                        $has_unused_themes = true;
565                        $themes_inactive   = ( $themes_total - $allowed_theme_count );
566                }
567
568                // Check if any themes need to be updated.
569                if ( $themes_need_updates > 0 ) {
570                        $result['status'] = 'critical';
571
572                        $result['label'] = __( 'You have themes waiting to be updated' );
573
574                        $result['description'] .= sprintf(
575                                '<p>%s</p>',
576                                sprintf(
577                                        /* translators: %d: The number of outdated themes. */
578                                        _n(
579                                                'Your site has %d theme waiting to be updated.',
580                                                'Your site has %d themes waiting to be updated.',
581                                                $themes_need_updates
582                                        ),
583                                        $themes_need_updates
584                                )
585                        );
586                } else {
587                        // Give positive feedback about the site being good about keeping things up to date.
588                        if ( 1 === $themes_total ) {
589                                $result['description'] .= sprintf(
590                                        '<p>%s</p>',
591                                        __( 'Your site has 1 installed theme, and it is up to date.' )
592                                );
593                        } elseif ( $themes_total > 0 ) {
594                                $result['description'] .= sprintf(
595                                        '<p>%s</p>',
596                                        sprintf(
597                                                /* translators: %d: The number of themes. */
598                                                _n(
599                                                        'Your site has %d installed theme, and it is up to date.',
600                                                        'Your site has %d installed themes, and they are all up to date.',
601                                                        $themes_total
602                                                ),
603                                                $themes_total
604                                        )
605                                );
606                        } else {
607                                $result['description'] .= sprintf(
608                                        '<p>%s</p>',
609                                        __( 'Your site does not have any installed themes.' )
610                                );
611                        }
612                }
613
614                if ( $has_unused_themes && $show_unused_themes && ! is_multisite() ) {
615
616                        // This is a child theme, so we want to be a bit more explicit in our messages.
617                        if ( $active_theme->parent() ) {
618                                // Recommend removing inactive themes, except a default theme, your current one, and the parent theme.
619                                $result['status'] = 'recommended';
620
621                                $result['label'] = __( 'You should remove inactive themes' );
622
623                                if ( $using_default_theme ) {
624                                        $result['description'] .= sprintf(
625                                                '<p>%s %s</p>',
626                                                sprintf(
627                                                        /* translators: %d: The number of inactive themes. */
628                                                        _n(
629                                                                'Your site has %d inactive theme.',
630                                                                'Your site has %d inactive themes.',
631                                                                $themes_inactive
632                                                        ),
633                                                        $themes_inactive
634                                                ),
635                                                sprintf(
636                                                        /* translators: 1: The currently active theme. 2: The active theme's parent theme. */
637                                                        __( 'To enhance your site&#8217;s security, you should consider removing any themes you are not using. You should keep your active theme, %1$s, and %2$s, its parent theme.' ),
638                                                        $active_theme->name,
639                                                        $active_theme->parent()->name
640                                                )
641                                        );
642                                } else {
643                                        $result['description'] .= sprintf(
644                                                '<p>%s %s</p>',
645                                                sprintf(
646                                                        /* translators: %d: The number of inactive themes. */
647                                                        _n(
648                                                                'Your site has %d inactive theme.',
649                                                                'Your site has %d inactive themes.',
650                                                                $themes_inactive
651                                                        ),
652                                                        $themes_inactive
653                                                ),
654                                                sprintf(
655                                                        /* translators: 1: The default theme for WordPress. 2: The currently active theme. 3: The active theme's parent theme. */
656                                                        __( 'To enhance your site&#8217;s security, you should consider removing any themes you are not using. You should keep %1$s, the default WordPress theme, %2$s, your active theme, and %3$s, its parent theme.' ),
657                                                        $default_theme ? $default_theme->name : WP_DEFAULT_THEME,
658                                                        $active_theme->name,
659                                                        $active_theme->parent()->name
660                                                )
661                                        );
662                                }
663                        } else {
664                                // Recommend removing all inactive themes.
665                                $result['status'] = 'recommended';
666
667                                $result['label'] = __( 'You should remove inactive themes' );
668
669                                if ( $using_default_theme ) {
670                                        $result['description'] .= sprintf(
671                                                '<p>%s %s</p>',
672                                                sprintf(
673                                                        /* translators: 1: The amount of inactive themes. 2: The currently active theme. */
674                                                        _n(
675                                                                'Your site has %1$d inactive theme, other than %2$s, your active theme.',
676                                                                'Your site has %1$d inactive themes, other than %2$s, your active theme.',
677                                                                $themes_inactive
678                                                        ),
679                                                        $themes_inactive,
680                                                        $active_theme->name
681                                                ),
682                                                __( 'You should consider removing any unused themes to enhance your site&#8217;s security.' )
683                                        );
684                                } else {
685                                        $result['description'] .= sprintf(
686                                                '<p>%s %s</p>',
687                                                sprintf(
688                                                        /* translators: 1: The amount of inactive themes. 2: The default theme for WordPress. 3: The currently active theme. */
689                                                        _n(
690                                                                'Your site has %1$d inactive theme, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
691                                                                'Your site has %1$d inactive themes, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
692                                                                $themes_inactive
693                                                        ),
694                                                        $themes_inactive,
695                                                        $default_theme ? $default_theme->name : WP_DEFAULT_THEME,
696                                                        $active_theme->name
697                                                ),
698                                                __( 'You should consider removing any unused themes to enhance your site&#8217;s security.' )
699                                        );
700                                }
701                        }
702                }
703
704                // If no default Twenty* theme exists.
705                if ( ! $has_default_theme ) {
706                        $result['status'] = 'recommended';
707
708                        $result['label'] = __( 'Have a default theme available' );
709
710                        $result['description'] .= sprintf(
711                                '<p>%s</p>',
712                                __( 'Your site does not have any default theme. Default themes are used by WordPress automatically if anything is wrong with your chosen theme.' )
713                        );
714                }
715
716                return $result;
717        }
718
719        /**
720         * Tests if the supplied PHP version is supported.
721         *
722         * @since 5.2.0
723         *
724         * @return array The test results.
725         */
726        public function get_test_php_version() {
727                $response = wp_check_php_version();
728
729                $result = array(
730                        'label'       => sprintf(
731                                /* translators: %s: The current PHP version. */
732                                __( 'Your site is running the current version of PHP (%s)' ),
733                                PHP_VERSION
734                        ),
735                        'status'      => 'good',
736                        'badge'       => array(
737                                'label' => __( 'Performance' ),
738                                'color' => 'blue',
739                        ),
740                        'description' => sprintf(
741                                '<p>%s</p>',
742                                sprintf(
743                                        /* translators: %s: The minimum recommended PHP version. */
744                                        __( 'PHP is one of the programming languages used to build WordPress. Newer versions of PHP receive regular security updates and may increase your site&#8217;s performance. The minimum recommended version of PHP is %s.' ),
745                                        $response ? $response['recommended_version'] : ''
746                                )
747                        ),
748                        'actions'     => sprintf(
749                                '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
750                                esc_url( wp_get_update_php_url() ),
751                                __( 'Learn more about updating PHP' ),
752                                /* translators: Hidden accessibility text. */
753                                __( '(opens in a new tab)' )
754                        ),
755                        'test'        => 'php_version',
756                );
757
758                // PHP is up to date.
759                if ( ! $response || version_compare( PHP_VERSION, $response['recommended_version'], '>=' ) ) {
760                        return $result;
761                }
762
763                // The PHP version is older than the recommended version, but still receiving active support.
764                if ( $response['is_supported'] ) {
765                        $result['label'] = sprintf(
766                                /* translators: %s: The server PHP version. */
767                                __( 'Your site is running on an older version of PHP (%s)' ),
768                                PHP_VERSION
769                        );
770                        $result['status'] = 'recommended';
771
772                        return $result;
773                }
774
775                // The PHP version is still receiving security fixes, but is lower than
776                // the expected minimum version that will be required by WordPress in the near future.
777                if ( $response['is_secure'] && $response['is_lower_than_future_minimum'] ) {
778                        // The `is_secure` array key name doesn't actually imply this is a secure version of PHP. It only means it receives security updates.
779
780                        $result['label'] = sprintf(
781                                /* translators: %s: The server PHP version. */
782                                __( 'Your site is running on an outdated version of PHP (%s), which soon will not be supported by WordPress.' ),
783                                PHP_VERSION
784                        );
785
786                        $result['status']         = 'critical';
787                        $result['badge']['label'] = __( 'Requirements' );
788
789                        return $result;
790                }
791
792                // The PHP version is only receiving security fixes.
793                if ( $response['is_secure'] ) {
794                        $result['label'] = sprintf(
795                                /* translators: %s: The server PHP version. */
796                                __( 'Your site is running on an older version of PHP (%s), which should be updated' ),
797                                PHP_VERSION
798                        );
799                        $result['status'] = 'recommended';
800
801                        return $result;
802                }
803
804                // No more security updates for the PHP version, and lower than the expected minimum version required by WordPress.
805                if ( $response['is_lower_than_future_minimum'] ) {
806                        $message = sprintf(
807                                /* translators: %s: The server PHP version. */
808                                __( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates and soon will not be supported by WordPress.' ),
809                                PHP_VERSION
810                        );
811                } else {
812                        // No more security updates for the PHP version, must be updated.
813                        $message = sprintf(
814                                /* translators: %s: The server PHP version. */
815                                __( 'Your site is running on an outdated version of PHP (%s), which does not receive security updates. It should be updated.' ),
816                                PHP_VERSION
817                        );
818                }
819
820                $result['label']  = $message;
821                $result['status'] = 'critical';
822
823                $result['badge']['label'] = __( 'Security' );
824
825                return $result;
826        }
827
828        /**
829         * Checks if the passed extension or function are available.
830         *
831         * Make the check for available PHP modules into a simple boolean operator for a cleaner test runner.
832         *
833         * @since 5.2.0
834         * @since 5.3.0 The `$constant_name` and `$class_name` parameters were added.
835         *
836         * @param string $extension_name Optional. The extension name to test. Default null.
837         * @param string $function_name  Optional. The function name to test. Default null.
838         * @param string $constant_name  Optional. The constant name to test for. Default null.
839         * @param string $class_name     Optional. The class name to test for. Default null.
840         * @return bool Whether or not the extension and function are available.
841         */
842        private function test_php_extension_availability( $extension_name = null, $function_name = null, $constant_name = null, $class_name = null ) {
843                // If no extension or function is passed, claim to fail testing, as we have nothing to test against.
844                if ( ! $extension_name && ! $function_name && ! $constant_name && ! $class_name ) {
845                        return false;
846                }
847
848                if ( $extension_name && ! extension_loaded( $extension_name ) ) {
849                        return false;
850                }
851
852                if ( $function_name && ! function_exists( $function_name ) ) {
853                        return false;
854                }
855
856                if ( $constant_name && ! defined( $constant_name ) ) {
857                        return false;
858                }
859
860                if ( $class_name && ! class_exists( $class_name ) ) {
861                        return false;
862                }
863
864                return true;
865        }
866
867        /**
868         * Tests if required PHP modules are installed on the host.
869         *
870         * This test builds on the recommendations made by the WordPress Hosting Team
871         * as seen at https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions
872         *
873         * @since 5.2.0
874         *
875         * @return array
876         */
877        public function get_test_php_extensions() {
878                $result = array(
879                        'label'       => __( 'Required and recommended modules are installed' ),
880                        'status'      => 'good',
881                        'badge'       => array(
882                                'label' => __( 'Performance' ),
883                                'color' => 'blue',
884                        ),
885                        'description' => sprintf(
886                                '<p>%s</p><p>%s</p>',
887                                __( 'PHP modules perform most of the tasks on the server that make your site run. Any changes to these must be made by your server administrator.' ),
888                                sprintf(
889                                        /* translators: 1: Link to the hosting group page about recommended PHP modules. 2: Additional link attributes. 3: Accessibility text. */
890                                        __( 'The WordPress Hosting Team maintains a list of those modules, both recommended and required, in <a href="%1$s" %2$s>the team handbook%3$s</a>.' ),
891                                        /* translators: Localized team handbook, if one exists. */
892                                        esc_url( __( 'https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions' ) ),
893                                        'target="_blank" rel="noopener"',
894                                        sprintf(
895                                                ' <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span>',
896                                                /* translators: Hidden accessibility text. */
897                                                __( '(opens in a new tab)' )
898                                        )
899                                )
900                        ),
901                        'actions'     => '',
902                        'test'        => 'php_extensions',
903                );
904
905                $modules = array(
906                        'curl'      => array(
907                                'function' => 'curl_version',
908                                'required' => false,
909                        ),
910                        'dom'       => array(
911                                'class'    => 'DOMNode',
912                                'required' => false,
913                        ),
914                        'exif'      => array(
915                                'function' => 'exif_read_data',
916                                'required' => false,
917                        ),
918                        'fileinfo'  => array(
919                                'function' => 'finfo_file',
920                                'required' => false,
921                        ),
922                        'hash'      => array(
923                                'function' => 'hash',
924                                'required' => false,
925                        ),
926                        'imagick'   => array(
927                                'extension' => 'imagick',
928                                'required'  => false,
929                        ),
930                        'json'      => array(
931                                'function' => 'json_last_error',
932                                'required' => true,
933                        ),
934                        'mbstring'  => array(
935                                'function' => 'mb_check_encoding',
936                                'required' => false,
937                        ),
938                        'mysqli'    => array(
939                                'function' => 'mysqli_connect',
940                                'required' => false,
941                        ),
942                        'libsodium' => array(
943                                'constant'            => 'SODIUM_LIBRARY_VERSION',
944                                'required'            => false,
945                                'php_bundled_version' => '7.2.0',
946                        ),
947                        'openssl'   => array(
948                                'function' => 'openssl_encrypt',
949                                'required' => false,
950                        ),
951                        'pcre'      => array(
952                                'function' => 'preg_match',
953                                'required' => false,
954                        ),
955                        'mod_xml'   => array(
956                                'extension' => 'libxml',
957                                'required'  => false,
958                        ),
959                        'zip'       => array(
960                                'class'    => 'ZipArchive',
961                                'required' => false,
962                        ),
963                        'filter'    => array(
964                                'function' => 'filter_list',
965                                'required' => false,
966                        ),
967                        'gd'        => array(
968                                'extension'    => 'gd',
969                                'required'     => false,
970                                'fallback_for' => 'imagick',
971                        ),
972                        'iconv'     => array(
973                                'function' => 'iconv',
974                                'required' => false,
975                        ),
976                        'intl'      => array(
977                                'extension' => 'intl',
978                                'required'  => false,
979                        ),
980                        'mcrypt'    => array(
981                                'extension'    => 'mcrypt',
982                                'required'     => false,
983                                'fallback_for' => 'libsodium',
984                        ),
985                        'simplexml' => array(
986                                'extension'    => 'simplexml',
987                                'required'     => false,
988                                'fallback_for' => 'mod_xml',
989                        ),
990                        'xmlreader' => array(
991                                'extension'    => 'xmlreader',
992                                'required'     => false,
993                                'fallback_for' => 'mod_xml',
994                        ),
995                        'zlib'      => array(
996                                'extension'    => 'zlib',
997                                'required'     => false,
998                                'fallback_for' => 'zip',
999                        ),
1000                );
1001
1002                /**
1003                 * Filters the array representing all the modules we wish to test for.
1004                 *
1005                 * @since 5.2.0
1006                 * @since 5.3.0 The `$constant` and `$class` parameters were added.
1007                 *
1008                 * @param array $modules {
1009                 *     An associative array of modules to test for.
1010                 *
1011                 *     @type array ...$0 {
1012                 *         An associative array of module properties used during testing.
1013                 *         One of either `$function` or `$extension` must be provided, or they will fail by default.
1014                 *
1015                 *         @type string $function     Optional. A function name to test for the existence of.
1016                 *         @type string $extension    Optional. An extension to check if is loaded in PHP.
1017                 *         @type string $constant     Optional. A constant name to check for to verify an extension exists.
1018                 *         @type string $class        Optional. A class name to check for to verify an extension exists.
1019                 *         @type bool   $required     Is this a required feature or not.
1020                 *         @type string $fallback_for Optional. The module this module replaces as a fallback.
1021                 *     }
1022                 * }
1023                 */
1024                $modules = apply_filters( 'site_status_test_php_modules', $modules );
1025
1026                $failures = array();
1027
1028                foreach ( $modules as $library => $module ) {
1029                        $extension_name = ( isset( $module['extension'] ) ? $module['extension'] : null );
1030                        $function_name  = ( isset( $module['function'] ) ? $module['function'] : null );
1031                        $constant_name  = ( isset( $module['constant'] ) ? $module['constant'] : null );
1032                        $class_name     = ( isset( $module['class'] ) ? $module['class'] : null );
1033
1034                        // If this module is a fallback for another function, check if that other function passed.
1035                        if ( isset( $module['fallback_for'] ) ) {
1036                                /*
1037                                 * If that other function has a failure, mark this module as required for usual operations.
1038                                 * If that other function hasn't failed, skip this test as it's only a fallback.
1039                                 */
1040                                if ( isset( $failures[ $module['fallback_for'] ] ) ) {
1041                                        $module['required'] = true;
1042                                } else {
1043                                        continue;
1044                                }
1045                        }
1046
1047                        if ( ! $this->test_php_extension_availability( $extension_name, $function_name, $constant_name, $class_name )
1048                                && ( ! isset( $module['php_bundled_version'] )
1049                                        || version_compare( PHP_VERSION, $module['php_bundled_version'], '<' ) )
1050                        ) {
1051                                if ( $module['required'] ) {
1052                                        $result['status'] = 'critical';
1053
1054                                        $class = 'error';
1055                                        /* translators: Hidden accessibility text. */
1056                                        $screen_reader = __( 'Error' );
1057                                        $message       = sprintf(
1058                                                /* translators: %s: The module name. */
1059                                                __( 'The required module, %s, is not installed, or has been disabled.' ),
1060                                                $library
1061                                        );
1062                                } else {
1063                                        $class = 'warning';
1064                                        /* translators: Hidden accessibility text. */
1065                                        $screen_reader = __( 'Warning' );
1066                                        $message       = sprintf(
1067                                                /* translators: %s: The module name. */
1068                                                __( 'The optional module, %s, is not installed, or has been disabled.' ),
1069                                                $library
1070                                        );
1071                                }
1072
1073                                if ( ! $module['required'] && 'good' === $result['status'] ) {
1074                                        $result['status'] = 'recommended';
1075                                }
1076
1077                                $failures[ $library ] = "<span class='dashicons $class'><span class='screen-reader-text'>$screen_reader</span></span> $message";
1078                        }
1079                }
1080
1081                if ( ! empty( $failures ) ) {
1082                        $output = '<ul>';
1083
1084                        foreach ( $failures as $failure ) {
1085                                $output .= sprintf(
1086                                        '<li>%s</li>',
1087                                        $failure
1088                                );
1089                        }
1090
1091                        $output .= '</ul>';
1092                }
1093
1094                if ( 'good' !== $result['status'] ) {
1095                        if ( 'recommended' === $result['status'] ) {
1096                                $result['label'] = __( 'One or more recommended modules are missing' );
1097                        }
1098                        if ( 'critical' === $result['status'] ) {
1099                                $result['label'] = __( 'One or more required modules are missing' );
1100                        }
1101
1102                        $result['description'] .= $output;
1103                }
1104
1105                return $result;
1106        }
1107
1108        /**
1109         * Tests if the PHP default timezone is set to UTC.
1110         *
1111         * @since 5.3.1
1112         *
1113         * @return array The test results.
1114         */
1115        public function get_test_php_default_timezone() {
1116                $result = array(
1117                        'label'       => __( 'PHP default timezone is valid' ),
1118                        'status'      => 'good',
1119                        'badge'       => array(
1120                                'label' => __( 'Performance' ),
1121                                'color' => 'blue',
1122                        ),
1123                        'description' => sprintf(
1124                                '<p>%s</p>',
1125                                __( 'PHP default timezone was configured by WordPress on loading. This is necessary for correct calculations of dates and times.' )
1126                        ),
1127                        'actions'     => '',
1128                        'test'        => 'php_default_timezone',
1129                );
1130
1131                if ( 'UTC' !== date_default_timezone_get() ) {
1132                        $result['status'] = 'critical';
1133
1134                        $result['label'] = __( 'PHP default timezone is invalid' );
1135
1136                        $result['description'] = sprintf(
1137                                '<p>%s</p>',
1138                                sprintf(
1139                                        /* translators: %s: date_default_timezone_set() */
1140                                        __( 'PHP default timezone was changed after WordPress loading by a %s function call. This interferes with correct calculations of dates and times.' ),
1141                                        '<code>date_default_timezone_set()</code>'
1142                                )
1143                        );
1144                }
1145
1146                return $result;
1147        }
1148
1149        /**
1150         * Tests if there's an active PHP session that can affect loopback requests.
1151         *
1152         * @since 5.5.0
1153         *
1154         * @return array The test results.
1155         */
1156        public function get_test_php_sessions() {
1157                $result = array(
1158                        'label'       => __( 'No PHP sessions detected' ),
1159                        'status'      => 'good',
1160                        'badge'       => array(
1161                                'label' => __( 'Performance' ),
1162                                'color' => 'blue',
1163                        ),
1164                        'description' => sprintf(
1165                                '<p>%s</p>',
1166                                sprintf(
1167                                        /* translators: 1: session_start(), 2: session_write_close() */
1168                                        __( 'PHP sessions created by a %1$s function call may interfere with REST API and loopback requests. An active session should be closed by %2$s before making any HTTP requests.' ),
1169                                        '<code>session_start()</code>',
1170                                        '<code>session_write_close()</code>'
1171                                )
1172                        ),
1173                        'test'        => 'php_sessions',
1174                );
1175
1176                if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
1177                        $result['status'] = 'critical';
1178
1179                        $result['label'] = __( 'An active PHP session was detected' );
1180
1181                        $result['description'] = sprintf(
1182                                '<p>%s</p>',
1183                                sprintf(
1184                                        /* translators: 1: session_start(), 2: session_write_close() */
1185                                        __( 'A PHP session was created by a %1$s function call. This interferes with REST API and loopback requests. The session should be closed by %2$s before making any HTTP requests.' ),
1186                                        '<code>session_start()</code>',
1187                                        '<code>session_write_close()</code>'
1188                                )
1189                        );
1190                }
1191
1192                return $result;
1193        }
1194
1195        /**
1196         * Tests if the SQL server is up to date.
1197         *
1198         * @since 5.2.0
1199         *
1200         * @return array The test results.
1201         */
1202        public function get_test_sql_server() {
1203                if ( ! $this->mysql_server_version ) {
1204                        $this->prepare_sql_data();
1205                }
1206
1207                $result = array(
1208                        'label'       => __( 'SQL server is up to date' ),
1209                        'status'      => 'good',
1210                        'badge'       => array(
1211                                'label' => __( 'Performance' ),
1212                                'color' => 'blue',
1213                        ),
1214                        'description' => sprintf(
1215                                '<p>%s</p>',
1216                                __( 'The SQL server is a required piece of software for the database WordPress uses to store all your site&#8217;s content and settings.' )
1217                        ),
1218                        'actions'     => sprintf(
1219                                '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1220                                /* translators: Localized version of WordPress requirements if one exists. */
1221                                esc_url( __( 'https://wordpress.org/about/requirements/' ) ),
1222                                __( 'Learn more about what WordPress requires to run.' ),
1223                                /* translators: Hidden accessibility text. */
1224                                __( '(opens in a new tab)' )
1225                        ),
1226                        'test'        => 'sql_server',
1227                );
1228
1229                $db_dropin = file_exists( WP_CONTENT_DIR . '/db.php' );
1230
1231                if ( ! $this->is_recommended_mysql_version ) {
1232                        $result['status'] = 'recommended';
1233
1234                        $result['label'] = __( 'Outdated SQL server' );
1235
1236                        $result['description'] .= sprintf(
1237                                '<p>%s</p>',
1238                                sprintf(
1239                                        /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server recommended version number. */
1240                                        __( 'For optimal performance and security reasons, you should consider running %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
1241                                        ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
1242                                        $this->mysql_recommended_version
1243                                )
1244                        );
1245                }
1246
1247                if ( ! $this->is_acceptable_mysql_version ) {
1248                        $result['status'] = 'critical';
1249
1250                        $result['label']          = __( 'Severely outdated SQL server' );
1251                        $result['badge']['label'] = __( 'Security' );
1252
1253                        $result['description'] .= sprintf(
1254                                '<p>%s</p>',
1255                                sprintf(
1256                                        /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server minimum version number. */
1257                                        __( 'WordPress requires %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
1258                                        ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
1259                                        $this->mysql_required_version
1260                                )
1261                        );
1262                }
1263
1264                if ( $db_dropin ) {
1265                        $result['description'] .= sprintf(
1266                                '<p>%s</p>',
1267                                wp_kses(
1268                                        sprintf(
1269                                                /* translators: 1: The name of the drop-in. 2: The name of the database engine. */
1270                                                __( 'You are using a %1$s drop-in which might mean that a %2$s database is not being used.' ),
1271                                                '<code>wp-content/db.php</code>',
1272                                                ( $this->is_mariadb ? 'MariaDB' : 'MySQL' )
1273                                        ),
1274                                        array(
1275                                                'code' => true,
1276                                        )
1277                                )
1278                        );
1279                }
1280
1281                return $result;
1282        }
1283
1284        /**
1285         * Tests if the database server is capable of using utf8mb4.
1286         *
1287         * @since 5.2.0
1288         *
1289         * @global wpdb $wpdb WordPress database abstraction object.
1290         *
1291         * @return array The test results.
1292         */
1293        public function get_test_utf8mb4_support() {
1294                global $wpdb;
1295
1296                if ( ! $this->mysql_server_version ) {
1297                        $this->prepare_sql_data();
1298                }
1299
1300                $result = array(
1301                        'label'       => __( 'UTF8MB4 is supported' ),
1302                        'status'      => 'good',
1303                        'badge'       => array(
1304                                'label' => __( 'Performance' ),
1305                                'color' => 'blue',
1306                        ),
1307                        'description' => sprintf(
1308                                '<p>%s</p>',
1309                                __( 'UTF8MB4 is the character set WordPress prefers for database storage because it safely supports the widest set of characters and encodings, including Emoji, enabling better support for non-English languages.' )
1310                        ),
1311                        'actions'     => '',
1312                        'test'        => 'utf8mb4_support',
1313                );
1314
1315                if ( ! $this->is_mariadb ) {
1316                        if ( version_compare( $this->mysql_server_version, '5.5.3', '<' ) ) {
1317                                $result['status'] = 'recommended';
1318
1319                                $result['label'] = __( 'utf8mb4 requires a MySQL update' );
1320
1321                                $result['description'] .= sprintf(
1322                                        '<p>%s</p>',
1323                                        sprintf(
1324                                                /* translators: %s: Version number. */
1325                                                __( 'WordPress&#8217; utf8mb4 support requires MySQL version %s or greater. Please contact your server administrator.' ),
1326                                                '5.5.3'
1327                                        )
1328                                );
1329                        } else {
1330                                $result['description'] .= sprintf(
1331                                        '<p>%s</p>',
1332                                        __( 'Your MySQL version supports utf8mb4.' )
1333                                );
1334                        }
1335                } else { // MariaDB introduced utf8mb4 support in 5.5.0.
1336                        if ( version_compare( $this->mysql_server_version, '5.5.0', '<' ) ) {
1337                                $result['status'] = 'recommended';
1338
1339                                $result['label'] = __( 'utf8mb4 requires a MariaDB update' );
1340
1341                                $result['description'] .= sprintf(
1342                                        '<p>%s</p>',
1343                                        sprintf(
1344                                                /* translators: %s: Version number. */
1345                                                __( 'WordPress&#8217; utf8mb4 support requires MariaDB version %s or greater. Please contact your server administrator.' ),
1346                                                '5.5.0'
1347                                        )
1348                                );
1349                        } else {
1350                                $result['description'] .= sprintf(
1351                                        '<p>%s</p>',
1352                                        __( 'Your MariaDB version supports utf8mb4.' )
1353                                );
1354                        }
1355                }
1356
1357                if ( $wpdb->use_mysqli ) {
1358                        // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysqli_get_client_info
1359                        $mysql_client_version = mysqli_get_client_info();
1360                } else {
1361                        // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_get_client_info,PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
1362                        $mysql_client_version = mysql_get_client_info();
1363                }
1364
1365                /*
1366                 * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
1367                 * mysqlnd has supported utf8mb4 since 5.0.9.
1368                 */
1369                if ( false !== strpos( $mysql_client_version, 'mysqlnd' ) ) {
1370                        $mysql_client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $mysql_client_version );
1371                        if ( version_compare( $mysql_client_version, '5.0.9', '<' ) ) {
1372                                $result['status'] = 'recommended';
1373
1374                                $result['label'] = __( 'utf8mb4 requires a newer client library' );
1375
1376                                $result['description'] .= sprintf(
1377                                        '<p>%s</p>',
1378                                        sprintf(
1379                                                /* translators: 1: Name of the library, 2: Number of version. */
1380                                                __( 'WordPress&#8217; utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ),
1381                                                'mysqlnd',
1382                                                '5.0.9'
1383                                        )
1384                                );
1385                        }
1386                } else {
1387                        if ( version_compare( $mysql_client_version, '5.5.3', '<' ) ) {
1388                                $result['status'] = 'recommended';
1389
1390                                $result['label'] = __( 'utf8mb4 requires a newer client library' );
1391
1392                                $result['description'] .= sprintf(
1393                                        '<p>%s</p>',
1394                                        sprintf(
1395                                                /* translators: 1: Name of the library, 2: Number of version. */
1396                                                __( 'WordPress&#8217; utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ),
1397                                                'libmysql',
1398                                                '5.5.3'
1399                                        )
1400                                );
1401                        }
1402                }
1403
1404                return $result;
1405        }
1406
1407        /**
1408         * Tests if the site can communicate with WordPress.org.
1409         *
1410         * @since 5.2.0
1411         *
1412         * @return array The test results.
1413         */
1414        public function get_test_dotorg_communication() {
1415                $result = array(
1416                        'label'       => __( 'Can communicate with WordPress.org' ),
1417                        'status'      => '',
1418                        'badge'       => array(
1419                                'label' => __( 'Security' ),
1420                                'color' => 'blue',
1421                        ),
1422                        'description' => sprintf(
1423                                '<p>%s</p>',
1424                                __( 'Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.' )
1425                        ),
1426                        'actions'     => '',
1427                        'test'        => 'dotorg_communication',
1428                );
1429
1430                $wp_dotorg = wp_remote_get(
1431                        'https://api.wordpress.org',
1432                        array(
1433                                'timeout' => 10,
1434                        )
1435                );
1436                if ( ! is_wp_error( $wp_dotorg ) ) {
1437                        $result['status'] = 'good';
1438                } else {
1439                        $result['status'] = 'critical';
1440
1441                        $result['label'] = __( 'Could not reach WordPress.org' );
1442
1443                        $result['description'] .= sprintf(
1444                                '<p>%s</p>',
1445                                sprintf(
1446                                        '<span class="error"><span class="screen-reader-text">%s</span></span> %s',
1447                                        /* translators: Hidden accessibility text. */
1448                                        __( 'Error' ),
1449                                        sprintf(
1450                                                /* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */
1451                                                __( 'Your site is unable to reach WordPress.org at %1$s, and returned the error: %2$s' ),
1452                                                gethostbyname( 'api.wordpress.org' ),
1453                                                $wp_dotorg->get_error_message()
1454                                        )
1455                                )
1456                        );
1457
1458                        $result['actions'] = sprintf(
1459                                '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1460                                /* translators: Localized Support reference. */
1461                                esc_url( __( 'https://wordpress.org/support/forums/' ) ),
1462                                __( 'Get help resolving this issue.' ),
1463                                /* translators: Hidden accessibility text. */
1464                                __( '(opens in a new tab)' )
1465                        );
1466                }
1467
1468                return $result;
1469        }
1470
1471        /**
1472         * Tests if debug information is enabled.
1473         *
1474         * When WP_DEBUG is enabled, errors and information may be disclosed to site visitors,
1475         * or logged to a publicly accessible file.
1476         *
1477         * Debugging is also frequently left enabled after looking for errors on a site,
1478         * as site owners do not understand the implications of this.
1479         *
1480         * @since 5.2.0
1481         *
1482         * @return array The test results.
1483         */
1484        public function get_test_is_in_debug_mode() {
1485                $result = array(
1486                        'label'       => __( 'Your site is not set to output debug information' ),
1487                        'status'      => 'good',
1488                        'badge'       => array(
1489                                'label' => __( 'Security' ),
1490                                'color' => 'blue',
1491                        ),
1492                        'description' => sprintf(
1493                                '<p>%s</p>',
1494                                __( 'Debug mode is often enabled to gather more details about an error or site failure, but may contain sensitive information which should not be available on a publicly available website.' )
1495                        ),
1496                        'actions'     => sprintf(
1497                                '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1498                                /* translators: Documentation explaining debugging in WordPress. */
1499                                esc_url( __( 'https://wordpress.org/documentation/article/debugging-in-wordpress/' ) ),
1500                                __( 'Learn more about debugging in WordPress.' ),
1501                                /* translators: Hidden accessibility text. */
1502                                __( '(opens in a new tab)' )
1503                        ),
1504                        'test'        => 'is_in_debug_mode',
1505                );
1506
1507                if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
1508                        if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
1509                                $result['label'] = __( 'Your site is set to log errors to a potentially public file' );
1510
1511                                $result['status'] = ( 0 === strpos( ini_get( 'error_log' ), ABSPATH ) ) ? 'critical' : 'recommended';
1512
1513                                $result['description'] .= sprintf(
1514                                        '<p>%s</p>',
1515                                        sprintf(
1516                                                /* translators: %s: WP_DEBUG_LOG */
1517                                                __( 'The value, %s, has been added to this website&#8217;s configuration file. This means any errors on the site will be written to a file which is potentially available to all users.' ),
1518                                                '<code>WP_DEBUG_LOG</code>'
1519                                        )
1520                                );
1521                        }
1522
1523                        if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) {
1524                                $result['label'] = __( 'Your site is set to display errors to site visitors' );
1525
1526                                $result['status'] = 'critical';
1527
1528                                // On development environments, set the status to recommended.
1529                                if ( $this->is_development_environment() ) {
1530                                        $result['status'] = 'recommended';
1531                                }
1532
1533                                $result['description'] .= sprintf(
1534                                        '<p>%s</p>',
1535                                        sprintf(
1536                                                /* translators: 1: WP_DEBUG_DISPLAY, 2: WP_DEBUG */
1537                                                __( 'The value, %1$s, has either been enabled by %2$s or added to your configuration file. This will make errors display on the front end of your site.' ),
1538                                                '<code>WP_DEBUG_DISPLAY</code>',
1539                                                '<code>WP_DEBUG</code>'
1540                                        )
1541                                );
1542                        }
1543                }
1544
1545                return $result;
1546        }
1547
1548        /**
1549         * Tests if the site is serving content over HTTPS.
1550         *
1551         * Many sites have varying degrees of HTTPS support, the most common of which is sites that have it
1552         * enabled, but only if you visit the right site address.
1553         *
1554         * @since 5.2.0
1555         * @since 5.7.0 Updated to rely on {@see wp_is_using_https()} and {@see wp_is_https_supported()}.
1556         *
1557         * @return array The test results.
1558         */
1559        public function get_test_https_status() {
1560                // Enforce fresh HTTPS detection results. This is normally invoked by using cron,
1561                // but for Site Health it should always rely on the latest results.
1562                wp_update_https_detection_errors();
1563
1564                $default_update_url = wp_get_default_update_https_url();
1565
1566                $result = array(
1567                        'label'       => __( 'Your website is using an active HTTPS connection' ),
1568                        'status'      => 'good',
1569                        'badge'       => array(
1570                                'label' => __( 'Security' ),
1571                                'color' => 'blue',
1572                        ),
1573                        'description' => sprintf(
1574                                '<p>%s</p>',
1575                                __( 'An HTTPS connection is a more secure way of browsing the web. Many services now have HTTPS as a requirement. HTTPS allows you to take advantage of new features that can increase site speed, improve search rankings, and gain the trust of your visitors by helping to protect their online privacy.' )
1576                        ),
1577                        'actions'     => sprintf(
1578                                '<p><a href="%s" target="_blank" rel="noopener">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1579                                esc_url( $default_update_url ),
1580                                __( 'Learn more about why you should use HTTPS' ),
1581                                /* translators: Hidden accessibility text. */
1582                                __( '(opens in a new tab)' )
1583                        ),
1584                        'test'        => 'https_status',
1585                );
1586
1587                if ( ! wp_is_using_https() ) {
1588                        // If the website is not using HTTPS, provide more information
1589                        // about whether it is supported and how it can be enabled.
1590                        $result['status'] = 'recommended';
1591                        $result['label']  = __( 'Your website does not use HTTPS' );
1592
1593                        if ( wp_is_site_url_using_https() ) {
1594                                if ( is_ssl() ) {
1595                                        $result['description'] = sprintf(
1596                                                '<p>%s</p>',
1597                                                sprintf(
1598                                                        /* translators: %s: URL to Settings > General > Site Address. */
1599                                                        __( 'You are accessing this website using HTTPS, but your <a href="%s">Site Address</a> is not set up to use HTTPS by default.' ),
1600                                                        esc_url( admin_url( 'options-general.php' ) . '#home' )
1601                                                )
1602                                        );
1603                                } else {
1604                                        $result['description'] = sprintf(
1605                                                '<p>%s</p>',
1606                                                sprintf(
1607                                                        /* translators: %s: URL to Settings > General > Site Address. */
1608                                                        __( 'Your <a href="%s">Site Address</a> is not set up to use HTTPS.' ),
1609                                                        esc_url( admin_url( 'options-general.php' ) . '#home' )
1610                                                )
1611                                        );
1612                                }
1613                        } else {
1614                                if ( is_ssl() ) {
1615                                        $result['description'] = sprintf(
1616                                                '<p>%s</p>',
1617                                                sprintf(
1618                                                        /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
1619                                                        __( 'You are accessing this website using HTTPS, but your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS by default.' ),
1620                                                        esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
1621                                                        esc_url( admin_url( 'options-general.php' ) . '#home' )
1622                                                )
1623                                        );
1624                                } else {
1625                                        $result['description'] = sprintf(
1626                                                '<p>%s</p>',
1627                                                sprintf(
1628                                                        /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
1629                                                        __( 'Your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS.' ),
1630                                                        esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
1631                                                        esc_url( admin_url( 'options-general.php' ) . '#home' )
1632                                                )
1633                                        );
1634                                }
1635                        }
1636
1637                        if ( wp_is_https_supported() ) {
1638                                $result['description'] .= sprintf(
1639                                        '<p>%s</p>',
1640                                        __( 'HTTPS is already supported for your website.' )
1641                                );
1642
1643                                if ( defined( 'WP_HOME' ) || defined( 'WP_SITEURL' ) ) {
1644                                        $result['description'] .= sprintf(
1645                                                '<p>%s</p>',
1646                                                sprintf(
1647                                                        /* translators: 1: wp-config.php, 2: WP_HOME, 3: WP_SITEURL */
1648                                                        __( 'However, your WordPress Address is currently controlled by a PHP constant and therefore cannot be updated. You need to edit your %1$s and remove or update the definitions of %2$s and %3$s.' ),
1649                                                        '<code>wp-config.php</code>',
1650                                                        '<code>WP_HOME</code>',
1651                                                        '<code>WP_SITEURL</code>'
1652                                                )
1653                                        );
1654                                } elseif ( current_user_can( 'update_https' ) ) {
1655                                        $default_direct_update_url = add_query_arg( 'action', 'update_https', wp_nonce_url( admin_url( 'site-health.php' ), 'wp_update_https' ) );
1656                                        $direct_update_url         = wp_get_direct_update_https_url();
1657
1658                                        if ( ! empty( $direct_update_url ) ) {
1659                                                $result['actions'] = sprintf(
1660                                                        '<p class="button-container"><a class="button button-primary" href="%1$s" target="_blank" rel="noopener">%2$s<span class="screen-reader-text"> %3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1661                                                        esc_url( $direct_update_url ),
1662                                                        __( 'Update your site to use HTTPS' ),
1663                                                        /* translators: Hidden accessibility text. */
1664                                                        __( '(opens in a new tab)' )
1665                                                );
1666                                        } else {
1667                                                $result['actions'] = sprintf(
1668                                                        '<p class="button-container"><a class="button button-primary" href="%1$s">%2$s</a></p>',
1669                                                        esc_url( $default_direct_update_url ),
1670                                                        __( 'Update your site to use HTTPS' )
1671                                                );
1672                                        }
1673                                }
1674                        } else {
1675                                // If host-specific "Update HTTPS" URL is provided, include a link.
1676                                $update_url = wp_get_update_https_url();
1677                                if ( $update_url !== $default_update_url ) {
1678                                        $result['description'] .= sprintf(
1679                                                '<p><a href="%s" target="_blank" rel="noopener">%s<span class="screen-reader-text"> %s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1680                                                esc_url( $update_url ),
1681                                                __( 'Talk to your web host about supporting HTTPS for your website.' ),
1682                                                /* translators: Hidden accessibility text. */
1683                                                __( '(opens in a new tab)' )
1684                                        );
1685                                } else {
1686                                        $result['description'] .= sprintf(
1687                                                '<p>%s</p>',
1688                                                __( 'Talk to your web host about supporting HTTPS for your website.' )
1689                                        );
1690                                }
1691                        }
1692                }
1693
1694                return $result;
1695        }
1696
1697        /**
1698         * Checks if the HTTP API can handle SSL/TLS requests.
1699         *
1700         * @since 5.2.0
1701         *
1702         * @return array The test result.
1703         */
1704        public function get_test_ssl_support() {
1705                $result = array(
1706                        'label'       => '',
1707                        'status'      => '',
1708                        'badge'       => array(
1709                                'label' => __( 'Security' ),
1710                                'color' => 'blue',
1711                        ),
1712                        'description' => sprintf(
1713                                '<p>%s</p>',
1714                                __( 'Securely communicating between servers are needed for transactions such as fetching files, conducting sales on store sites, and much more.' )
1715                        ),
1716                        'actions'     => '',
1717                        'test'        => 'ssl_support',
1718                );
1719
1720                $supports_https = wp_http_supports( array( 'ssl' ) );
1721
1722                if ( $supports_https ) {
1723                        $result['status'] = 'good';
1724
1725                        $result['label'] = __( 'Your site can communicate securely with other services' );
1726                } else {
1727                        $result['status'] = 'critical';
1728
1729                        $result['label'] = __( 'Your site is unable to communicate securely with other services' );
1730
1731                        $result['description'] .= sprintf(
1732                                '<p>%s</p>',
1733                                __( 'Talk to your web host about OpenSSL support for PHP.' )
1734                        );
1735                }
1736
1737                return $result;
1738        }
1739
1740        /**
1741         * Tests if scheduled events run as intended.
1742         *
1743         * If scheduled events are not running, this may indicate something with WP_Cron is not working
1744         * as intended, or that there are orphaned events hanging around from older code.
1745         *
1746         * @since 5.2.0
1747         *
1748         * @return array The test results.
1749         */
1750        public function get_test_scheduled_events() {
1751                $result = array(
1752                        'label'       => __( 'Scheduled events are running' ),
1753                        'status'      => 'good',
1754                        'badge'       => array(
1755                                'label' => __( 'Performance' ),
1756                                'color' => 'blue',
1757                        ),
1758                        'description' => sprintf(
1759                                '<p>%s</p>',
1760                                __( 'Scheduled events are what periodically looks for updates to plugins, themes and WordPress itself. It is also what makes sure scheduled posts are published on time. It may also be used by various plugins to make sure that planned actions are executed.' )
1761                        ),
1762                        'actions'     => '',
1763                        'test'        => 'scheduled_events',
1764                );
1765
1766                $this->wp_schedule_test_init();
1767
1768                if ( is_wp_error( $this->has_missed_cron() ) ) {
1769                        $result['status'] = 'critical';
1770
1771                        $result['label'] = __( 'It was not possible to check your scheduled events' );
1772
1773                        $result['description'] = sprintf(
1774                                '<p>%s</p>',
1775                                sprintf(
1776                                        /* translators: %s: The error message returned while from the cron scheduler. */
1777                                        __( 'While trying to test your site&#8217;s scheduled events, the following error was returned: %s' ),
1778                                        $this->has_missed_cron()->get_error_message()
1779                                )
1780                        );
1781                } elseif ( $this->has_missed_cron() ) {
1782                        $result['status'] = 'recommended';
1783
1784                        $result['label'] = __( 'A scheduled event has failed' );
1785
1786                        $result['description'] = sprintf(
1787                                '<p>%s</p>',
1788                                sprintf(
1789                                        /* translators: %s: The name of the failed cron event. */
1790                                        __( 'The scheduled event, %s, failed to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ),
1791                                        $this->last_missed_cron
1792                                )
1793                        );
1794                } elseif ( $this->has_late_cron() ) {
1795                        $result['status'] = 'recommended';
1796
1797                        $result['label'] = __( 'A scheduled event is late' );
1798
1799                        $result['description'] = sprintf(
1800                                '<p>%s</p>',
1801                                sprintf(
1802                                        /* translators: %s: The name of the late cron event. */
1803                                        __( 'The scheduled event, %s, is late to run. Your site still works, but this may indicate that scheduling posts or automated updates may not work as intended.' ),
1804                                        $this->last_late_cron
1805                                )
1806                        );
1807                }
1808
1809                return $result;
1810        }
1811
1812        /**
1813         * Tests if WordPress can run automated background updates.
1814         *
1815         * Background updates in WordPress are primarily used for minor releases and security updates.
1816         * It's important to either have these working, or be aware that they are intentionally disabled
1817         * for whatever reason.
1818         *
1819         * @since 5.2.0
1820         *
1821         * @return array The test results.
1822         */
1823        public function get_test_background_updates() {
1824                $result = array(
1825                        'label'       => __( 'Background updates are working' ),
1826                        'status'      => 'good',
1827                        'badge'       => array(
1828                                'label' => __( 'Security' ),
1829                                'color' => 'blue',
1830                        ),
1831                        'description' => sprintf(
1832                                '<p>%s</p>',
1833                                __( 'Background updates ensure that WordPress can auto-update if a security update is released for the version you are currently using.' )
1834                        ),
1835                        'actions'     => '',
1836                        'test'        => 'background_updates',
1837                );
1838
1839                if ( ! class_exists( 'WP_Site_Health_Auto_Updates' ) ) {
1840                        require_once ABSPATH . 'wp-admin/includes/class-wp-site-health-auto-updates.php';
1841                }
1842
1843                // Run the auto-update tests in a separate class,
1844                // as there are many considerations to be made.
1845                $automatic_updates = new WP_Site_Health_Auto_Updates();
1846                $tests             = $automatic_updates->run_tests();
1847
1848                $output = '<ul>';
1849
1850                foreach ( $tests as $test ) {
1851                        /* translators: Hidden accessibility text. */
1852                        $severity_string = __( 'Passed' );
1853
1854                        if ( 'fail' === $test->severity ) {
1855                                $result['label'] = __( 'Background updates are not working as expected' );
1856
1857                                $result['status'] = 'critical';
1858
1859                                /* translators: Hidden accessibility text. */
1860                                $severity_string = __( 'Error' );
1861                        }
1862
1863                        if ( 'warning' === $test->severity && 'good' === $result['status'] ) {
1864                                $result['label'] = __( 'Background updates may not be working properly' );
1865
1866                                $result['status'] = 'recommended';
1867
1868                                /* translators: Hidden accessibility text. */
1869                                $severity_string = __( 'Warning' );
1870                        }
1871
1872                        $output .= sprintf(
1873                                '<li><span class="dashicons %s"><span class="screen-reader-text">%s</span></span> %s</li>',
1874                                esc_attr( $test->severity ),
1875                                $severity_string,
1876                                $test->description
1877                        );
1878                }
1879
1880                $output .= '</ul>';
1881
1882                if ( 'good' !== $result['status'] ) {
1883                        $result['description'] .= $output;
1884                }
1885
1886                return $result;
1887        }
1888
1889        /**
1890         * Tests if plugin and theme auto-updates appear to be configured correctly.
1891         *
1892         * @since 5.5.0
1893         *
1894         * @return array The test results.
1895         */
1896        public function get_test_plugin_theme_auto_updates() {
1897                $result = array(
1898                        'label'       => __( 'Plugin and theme auto-updates appear to be configured correctly' ),
1899                        'status'      => 'good',
1900                        'badge'       => array(
1901                                'label' => __( 'Security' ),
1902                                'color' => 'blue',
1903                        ),
1904                        'description' => sprintf(
1905                                '<p>%s</p>',
1906                                __( 'Plugin and theme auto-updates ensure that the latest versions are always installed.' )
1907                        ),
1908                        'actions'     => '',
1909                        'test'        => 'plugin_theme_auto_updates',
1910                );
1911
1912                $check_plugin_theme_updates = $this->detect_plugin_theme_auto_update_issues();
1913
1914                $result['status'] = $check_plugin_theme_updates->status;
1915
1916                if ( 'good' !== $result['status'] ) {
1917                        $result['label'] = __( 'Your site may have problems auto-updating plugins and themes' );
1918
1919                        $result['description'] .= sprintf(
1920                                '<p>%s</p>',
1921                                $check_plugin_theme_updates->message
1922                        );
1923                }
1924
1925                return $result;
1926        }
1927
1928        /**
1929         * Tests if loopbacks work as expected.
1930         *
1931         * A loopback is when WordPress queries itself, for example to start a new WP_Cron instance,
1932         * or when editing a plugin or theme. This has shown itself to be a recurring issue,
1933         * as code can very easily break this interaction.
1934         *
1935         * @since 5.2.0
1936         *
1937         * @return array The test results.
1938         */
1939        public function get_test_loopback_requests() {
1940                $result = array(
1941                        'label'       => __( 'Your site can perform loopback requests' ),
1942                        'status'      => 'good',
1943                        'badge'       => array(
1944                                'label' => __( 'Performance' ),
1945                                'color' => 'blue',
1946                        ),
1947                        'description' => sprintf(
1948                                '<p>%s</p>',
1949                                __( 'Loopback requests are used to run scheduled events, and are also used by the built-in editors for themes and plugins to verify code stability.' )
1950                        ),
1951                        'actions'     => '',
1952                        'test'        => 'loopback_requests',
1953                );
1954
1955                $check_loopback = $this->can_perform_loopback();
1956
1957                $result['status'] = $check_loopback->status;
1958
1959                if ( 'good' !== $result['status'] ) {
1960                        $result['label'] = __( 'Your site could not complete a loopback request' );
1961
1962                        $result['description'] .= sprintf(
1963                                '<p>%s</p>',
1964                                $check_loopback->message
1965                        );
1966                }
1967
1968                return $result;
1969        }
1970
1971        /**
1972         * Tests if HTTP requests are blocked.
1973         *
1974         * It's possible to block all outgoing communication (with the possibility of allowing certain
1975         * hosts) via the HTTP API. This may create problems for users as many features are running as
1976         * services these days.
1977         *
1978         * @since 5.2.0
1979         *
1980         * @return array The test results.
1981         */
1982        public function get_test_http_requests() {
1983                $result = array(
1984                        'label'       => __( 'HTTP requests seem to be working as expected' ),
1985                        'status'      => 'good',
1986                        'badge'       => array(
1987                                'label' => __( 'Performance' ),
1988                                'color' => 'blue',
1989                        ),
1990                        'description' => sprintf(
1991                                '<p>%s</p>',
1992                                __( 'It is possible for site maintainers to block all, or some, communication to other sites and services. If set up incorrectly, this may prevent plugins and themes from working as intended.' )
1993                        ),
1994                        'actions'     => '',
1995                        'test'        => 'http_requests',
1996                );
1997
1998                $blocked = false;
1999                $hosts   = array();
2000
2001                if ( defined( 'WP_HTTP_BLOCK_EXTERNAL' ) && WP_HTTP_BLOCK_EXTERNAL ) {
2002                        $blocked = true;
2003                }
2004
2005                if ( defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
2006                        $hosts = explode( ',', WP_ACCESSIBLE_HOSTS );
2007                }
2008
2009                if ( $blocked && 0 === count( $hosts ) ) {
2010                        $result['status'] = 'critical';
2011
2012                        $result['label'] = __( 'HTTP requests are blocked' );
2013
2014                        $result['description'] .= sprintf(
2015                                '<p>%s</p>',
2016                                sprintf(
2017                                        /* translators: %s: Name of the constant used. */
2018                                        __( 'HTTP requests have been blocked by the %s constant, with no allowed hosts.' ),
2019                                        '<code>WP_HTTP_BLOCK_EXTERNAL</code>'
2020                                )
2021                        );
2022                }
2023
2024                if ( $blocked && 0 < count( $hosts ) ) {
2025                        $result['status'] = 'recommended';
2026
2027                        $result['label'] = __( 'HTTP requests are partially blocked' );
2028
2029                        $result['description'] .= sprintf(
2030                                '<p>%s</p>',
2031                                sprintf(
2032                                        /* translators: 1: Name of the constant used. 2: List of allowed hostnames. */
2033                                        __( 'HTTP requests have been blocked by the %1$s constant, with some allowed hosts: %2$s.' ),
2034                                        '<code>WP_HTTP_BLOCK_EXTERNAL</code>',
2035                                        implode( ',', $hosts )
2036                                )
2037                        );
2038                }
2039
2040                return $result;
2041        }
2042
2043        /**
2044         * Tests if the REST API is accessible.
2045         *
2046         * Various security measures may block the REST API from working, or it may have been disabled in general.
2047         * This is required for the new block editor to work, so we explicitly test for this.
2048         *
2049         * @since 5.2.0
2050         *
2051         * @return array The test results.
2052         */
2053        public function get_test_rest_availability() {
2054                $result = array(
2055                        'label'       => __( 'The REST API is available' ),
2056                        'status'      => 'good',
2057                        'badge'       => array(
2058                                'label' => __( 'Performance' ),
2059                                'color' => 'blue',
2060                        ),
2061                        'description' => sprintf(
2062                                '<p>%s</p>',
2063                                __( 'The REST API is one way that WordPress and other applications communicate with the server. For example, the block editor screen relies on the REST API to display and save your posts and pages.' )
2064                        ),
2065                        'actions'     => '',
2066                        'test'        => 'rest_availability',
2067                );
2068
2069                $cookies = wp_unslash( $_COOKIE );
2070                $timeout = 10; // 10 seconds.
2071                $headers = array(
2072                        'Cache-Control' => 'no-cache',
2073                        'X-WP-Nonce'    => wp_create_nonce( 'wp_rest' ),
2074                );
2075                /** This filter is documented in wp-includes/class-wp-http-streams.php */
2076                $sslverify = apply_filters( 'https_local_ssl_verify', false );
2077
2078                // Include Basic auth in loopback requests.
2079                if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
2080                        $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
2081                }
2082
2083                $url = rest_url( 'wp/v2/types/post' );
2084
2085                // The context for this is editing with the new block editor.
2086                $url = add_query_arg(
2087                        array(
2088                                'context' => 'edit',
2089                        ),
2090                        $url
2091                );
2092
2093                $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
2094
2095                if ( is_wp_error( $r ) ) {
2096                        $result['status'] = 'critical';
2097
2098                        $result['label'] = __( 'The REST API encountered an error' );
2099
2100                        $result['description'] .= sprintf(
2101                                '<p>%s</p><p>%s<br>%s</p>',
2102                                __( 'When testing the REST API, an error was encountered:' ),
2103                                sprintf(
2104                                        // translators: %s: The REST API URL.
2105                                        __( 'REST API Endpoint: %s' ),
2106                                        $url
2107                                ),
2108                                sprintf(
2109                                        // translators: 1: The WordPress error code. 2: The WordPress error message.
2110                                        __( 'REST API Response: (%1$s) %2$s' ),
2111                                        $r->get_error_code(),
2112                                        $r->get_error_message()
2113                                )
2114                        );
2115                } elseif ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
2116                        $result['status'] = 'recommended';
2117
2118                        $result['label'] = __( 'The REST API encountered an unexpected result' );
2119
2120                        $result['description'] .= sprintf(
2121                                '<p>%s</p><p>%s<br>%s</p>',
2122                                __( 'When testing the REST API, an unexpected result was returned:' ),
2123                                sprintf(
2124                                        // translators: %s: The REST API URL.
2125                                        __( 'REST API Endpoint: %s' ),
2126                                        $url
2127                                ),
2128                                sprintf(
2129                                        // translators: 1: The WordPress error code. 2: The HTTP status code error message.
2130                                        __( 'REST API Response: (%1$s) %2$s' ),
2131                                        wp_remote_retrieve_response_code( $r ),
2132                                        wp_remote_retrieve_response_message( $r )
2133                                )
2134                        );
2135                } else {
2136                        $json = json_decode( wp_remote_retrieve_body( $r ), true );
2137
2138                        if ( false !== $json && ! isset( $json['capabilities'] ) ) {
2139                                $result['status'] = 'recommended';
2140
2141                                $result['label'] = __( 'The REST API did not behave correctly' );
2142
2143                                $result['description'] .= sprintf(
2144                                        '<p>%s</p>',
2145                                        sprintf(
2146                                                /* translators: %s: The name of the query parameter being tested. */
2147                                                __( 'The REST API did not process the %s query parameter correctly.' ),
2148                                                '<code>context</code>'
2149                                        )
2150                                );
2151                        }
2152                }
2153
2154                return $result;
2155        }
2156
2157        /**
2158         * Tests if 'file_uploads' directive in PHP.ini is turned off.
2159         *
2160         * @since 5.5.0
2161         *
2162         * @return array The test results.
2163         */
2164        public function get_test_file_uploads() {
2165                $result = array(
2166                        'label'       => __( 'Files can be uploaded' ),
2167                        'status'      => 'good',
2168                        'badge'       => array(
2169                                'label' => __( 'Performance' ),
2170                                'color' => 'blue',
2171                        ),
2172                        'description' => sprintf(
2173                                '<p>%s</p>',
2174                                sprintf(
2175                                        /* translators: 1: file_uploads, 2: php.ini */
2176                                        __( 'The %1$s directive in %2$s determines if uploading files is allowed on your site.' ),
2177                                        '<code>file_uploads</code>',
2178                                        '<code>php.ini</code>'
2179                                )
2180                        ),
2181                        'actions'     => '',
2182                        'test'        => 'file_uploads',
2183                );
2184
2185                if ( ! function_exists( 'ini_get' ) ) {
2186                        $result['status']       = 'critical';
2187                        $result['description'] .= sprintf(
2188                                /* translators: %s: ini_get() */
2189                                __( 'The %s function has been disabled, some media settings are unavailable because of this.' ),
2190                                '<code>ini_get()</code>'
2191                        );
2192                        return $result;
2193                }
2194
2195                if ( empty( ini_get( 'file_uploads' ) ) ) {
2196                        $result['status']       = 'critical';
2197                        $result['description'] .= sprintf(
2198                                '<p>%s</p>',
2199                                sprintf(
2200                                        /* translators: 1: file_uploads, 2: 0 */
2201                                        __( '%1$s is set to %2$s. You won\'t be able to upload files on your site.' ),
2202                                        '<code>file_uploads</code>',
2203                                        '<code>0</code>'
2204                                )
2205                        );
2206                        return $result;
2207                }
2208
2209                $post_max_size       = ini_get( 'post_max_size' );
2210                $upload_max_filesize = ini_get( 'upload_max_filesize' );
2211
2212                if ( wp_convert_hr_to_bytes( $post_max_size ) < wp_convert_hr_to_bytes( $upload_max_filesize ) ) {
2213                        $result['label'] = sprintf(
2214                                /* translators: 1: post_max_size, 2: upload_max_filesize */
2215                                __( 'The "%1$s" value is smaller than "%2$s"' ),
2216                                'post_max_size',
2217                                'upload_max_filesize'
2218                        );
2219                        $result['status'] = 'recommended';
2220
2221                        if ( 0 === wp_convert_hr_to_bytes( $post_max_size ) ) {
2222                                $result['description'] = sprintf(
2223                                        '<p>%s</p>',
2224                                        sprintf(
2225                                                /* translators: 1: post_max_size, 2: upload_max_filesize */
2226                                                __( 'The setting for %1$s is currently configured as 0, this could cause some problems when trying to upload files through plugin or theme features that rely on various upload methods. It is recommended to configure this setting to a fixed value, ideally matching the value of %2$s, as some upload methods read the value 0 as either unlimited, or disabled.' ),
2227                                                '<code>post_max_size</code>',
2228                                                '<code>upload_max_filesize</code>'
2229                                        )
2230                                );
2231                        } else {
2232                                $result['description'] = sprintf(
2233                                        '<p>%s</p>',
2234                                        sprintf(
2235                                                /* translators: 1: post_max_size, 2: upload_max_filesize */
2236                                                __( 'The setting for %1$s is smaller than %2$s, this could cause some problems when trying to upload files.' ),
2237                                                '<code>post_max_size</code>',
2238                                                '<code>upload_max_filesize</code>'
2239                                        )
2240                                );
2241                        }
2242
2243                        return $result;
2244                }
2245
2246                return $result;
2247        }
2248
2249        /**
2250         * Tests if the Authorization header has the expected values.
2251         *
2252         * @since 5.6.0
2253         *
2254         * @return array
2255         */
2256        public function get_test_authorization_header() {
2257                $result = array(
2258                        'label'       => __( 'The Authorization header is working as expected' ),
2259                        'status'      => 'good',
2260                        'badge'       => array(
2261                                'label' => __( 'Security' ),
2262                                'color' => 'blue',
2263                        ),
2264                        'description' => sprintf(
2265                                '<p>%s</p>',
2266                                __( 'The Authorization header is used by third-party applications you have approved for this site. Without this header, those apps cannot connect to your site.' )
2267                        ),
2268                        'actions'     => '',
2269                        'test'        => 'authorization_header',
2270                );
2271
2272                if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
2273                        $result['label'] = __( 'The authorization header is missing' );
2274                } elseif ( 'user' !== $_SERVER['PHP_AUTH_USER'] || 'pwd' !== $_SERVER['PHP_AUTH_PW'] ) {
2275                        $result['label'] = __( 'The authorization header is invalid' );
2276                } else {
2277                        return $result;
2278                }
2279
2280                $result['status']       = 'recommended';
2281                $result['description'] .= sprintf(
2282                        '<p>%s</p>',
2283                        __( 'If you are still seeing this warning after having tried the actions below, you may need to contact your hosting provider for further assistance.' )
2284                );
2285
2286                if ( ! function_exists( 'got_mod_rewrite' ) ) {
2287                        require_once ABSPATH . 'wp-admin/includes/misc.php';
2288                }
2289
2290                if ( got_mod_rewrite() ) {
2291                        $result['actions'] .= sprintf(
2292                                '<p><a href="%s">%s</a></p>',
2293                                esc_url( admin_url( 'options-permalink.php' ) ),
2294                                __( 'Flush permalinks' )
2295                        );
2296                } else {
2297                        $result['actions'] .= sprintf(
2298                                '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
2299                                __( 'https://developer.wordpress.org/rest-api/frequently-asked-questions/#why-is-authentication-not-working' ),
2300                                __( 'Learn how to configure the Authorization header.' ),
2301                                /* translators: Hidden accessibility text. */
2302                                __( '(opens in a new tab)' )
2303                        );
2304                }
2305
2306                return $result;
2307        }
2308
2309        /**
2310         * Tests if a full page cache is available.
2311         *
2312         * @since 6.1.0
2313         *
2314         * @return array The test result.
2315         */
2316        public function get_test_page_cache() {
2317                $description  = '<p>' . __( 'Page cache enhances the speed and performance of your site by saving and serving static pages instead of calling for a page every time a user visits.' ) . '</p>';
2318                $description .= '<p>' . __( 'Page cache is detected by looking for an active page cache plugin as well as making three requests to the homepage and looking for one or more of the following HTTP client caching response headers:' ) . '</p>';
2319                $description .= '<code>' . implode( '</code>, <code>', array_keys( $this->get_page_cache_headers() ) ) . '.</code>';
2320
2321                $result = array(
2322                        'badge'       => array(
2323                                'label' => __( 'Performance' ),
2324                                'color' => 'blue',
2325                        ),
2326                        'description' => wp_kses_post( $description ),
2327                        'test'        => 'page_cache',
2328                        'status'      => 'good',
2329                        'label'       => '',
2330                        'actions'     => sprintf(
2331                                '<p><a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s <span class="screen-reader-text">%3$s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
2332                                __( 'https://wordpress.org/documentation/article/optimization/#Caching' ),
2333                                __( 'Learn more about page cache' ),
2334                                /* translators: Hidden accessibility text. */
2335                                __( '(opens in a new tab)' )
2336                        ),
2337                );
2338
2339                $page_cache_detail = $this->get_page_cache_detail();
2340
2341                if ( is_wp_error( $page_cache_detail ) ) {
2342                        $result['label']  = __( 'Unable to detect the presence of page cache' );
2343                        $result['status'] = 'recommended';
2344                        $error_info       = sprintf(
2345                        /* translators: 1: Error message, 2: Error code. */
2346                                __( 'Unable to detect page cache due to possible loopback request problem. Please verify that the loopback request test is passing. Error: %1$s (Code: %2$s)' ),
2347                                $page_cache_detail->get_error_message(),
2348                                $page_cache_detail->get_error_code()
2349                        );
2350                        $result['description'] = wp_kses_post( "<p>$error_info</p>" ) . $result['description'];
2351                        return $result;
2352                }
2353
2354                $result['status'] = $page_cache_detail['status'];
2355
2356                switch ( $page_cache_detail['status'] ) {
2357                        case 'recommended':
2358                                $result['label'] = __( 'Page cache is not detected but the server response time is OK' );
2359                                break;
2360                        case 'good':
2361                                $result['label'] = __( 'Page cache is detected and the server response time is good' );
2362                                break;
2363                        default:
2364                                if ( empty( $page_cache_detail['headers'] ) && ! $page_cache_detail['advanced_cache_present'] ) {
2365                                        $result['label'] = __( 'Page cache is not detected and the server response time is slow' );
2366                                } else {
2367                                        $result['label'] = __( 'Page cache is detected but the server response time is still slow' );
2368                                }
2369                }
2370
2371                $page_cache_test_summary = array();
2372
2373                if ( empty( $page_cache_detail['response_time'] ) ) {
2374                        $page_cache_test_summary[] = '<span class="dashicons dashicons-dismiss"></span> ' . __( 'Server response time could not be determined. Verify that loopback requests are working.' );
2375                } else {
2376
2377                        $threshold = $this->get_good_response_time_threshold();
2378                        if ( $page_cache_detail['response_time'] < $threshold ) {
2379                                $page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt"></span> ' . sprintf(
2380                                        /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
2381                                        __( 'Median server response time was %1$s milliseconds. This is less than the recommended %2$s milliseconds threshold.' ),
2382                                        number_format_i18n( $page_cache_detail['response_time'] ),
2383                                        number_format_i18n( $threshold )
2384                                );
2385                        } else {
2386                                $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . sprintf(
2387                                        /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
2388                                        __( 'Median server response time was %1$s milliseconds. It should be less than the recommended %2$s milliseconds threshold.' ),
2389                                        number_format_i18n( $page_cache_detail['response_time'] ),
2390                                        number_format_i18n( $threshold )
2391                                );
2392                        }
2393
2394                        if ( empty( $page_cache_detail['headers'] ) ) {
2395                                $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . __( 'No client caching response headers were detected.' );
2396                        } else {
2397                                $headers_summary  = '<span class="dashicons dashicons-yes-alt"></span>';
2398                                $headers_summary .= ' ' . sprintf(
2399                                        /* translators: %d: Number of caching headers. */
2400                                        _n(
2401                                                'There was %d client caching response header detected:',
2402                                                'There were %d client caching response headers detected:',
2403                                                count( $page_cache_detail['headers'] )
2404                                        ),
2405                                        count( $page_cache_detail['headers'] )
2406                                );
2407                                $headers_summary          .= ' <code>' . implode( '</code>, <code>', $page_cache_detail['headers'] ) . '</code>.';
2408                                $page_cache_test_summary[] = $headers_summary;
2409                        }
2410                }
2411
2412                if ( $page_cache_detail['advanced_cache_present'] ) {
2413                        $page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt"></span> ' . __( 'A page cache plugin was detected.' );
2414                } elseif ( ! ( is_array( $page_cache_detail ) && ! empty( $page_cache_detail['headers'] ) ) ) {
2415                        // Note: This message is not shown if client caching response headers were present since an external caching layer may be employed.
2416                        $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . __( 'A page cache plugin was not detected.' );
2417                }
2418
2419                $result['description'] .= '<ul><li>' . implode( '</li><li>', $page_cache_test_summary ) . '</li></ul>';
2420                return $result;
2421        }
2422
2423        /**
2424         * Tests if the site uses persistent object cache and recommends to use it if not.
2425         *
2426         * @since 6.1.0
2427         *
2428         * @return array The test result.
2429         */
2430        public function get_test_persistent_object_cache() {
2431                /**
2432                 * Filters the action URL for the persistent object cache health check.
2433                 *
2434                 * @since 6.1.0
2435                 *
2436                 * @param string $action_url Learn more link for persistent object cache health check.
2437                 */
2438                $action_url = apply_filters(
2439                        'site_status_persistent_object_cache_url',
2440                        /* translators: Localized Support reference. */
2441                        __( 'https://wordpress.org/documentation/article/optimization/#persistent-object-cache' )
2442                );
2443
2444                $result = array(
2445                        'test'        => 'persistent_object_cache',
2446                        'status'      => 'good',
2447                        'badge'       => array(
2448                                'label' => __( 'Performance' ),
2449                                'color' => 'blue',
2450                        ),
2451                        'label'       => __( 'A persistent object cache is being used' ),
2452                        'description' => sprintf(
2453                                '<p>%s</p>',
2454                                __( 'A persistent object cache makes your site&#8217;s database more efficient, resulting in faster load times because WordPress can retrieve your site&#8217;s content and settings much more quickly.' )
2455                        ),
2456                        'actions'     => sprintf(
2457                                '<p><a href="%s" target="_blank" rel="noopener">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
2458                                esc_url( $action_url ),
2459                                __( 'Learn more about persistent object caching.' ),
2460                                /* translators: Hidden accessibility text. */
2461                                __( '(opens in a new tab)' )
2462                        ),
2463                );
2464
2465                if ( wp_using_ext_object_cache() ) {
2466                        return $result;
2467                }
2468
2469                if ( ! $this->should_suggest_persistent_object_cache() ) {
2470                        $result['label'] = __( 'A persistent object cache is not required' );
2471
2472                        return $result;
2473                }
2474
2475                $available_services = $this->available_object_cache_services();
2476
2477                $notes = __( 'Your hosting provider can tell you if a persistent object cache can be enabled on your site.' );
2478
2479                if ( ! empty( $available_services ) ) {
2480                        $notes .= ' ' . sprintf(
2481                                /* translators: Available object caching services. */
2482                                __( 'Your host appears to support the following object caching services: %s.' ),
2483                                implode( ', ', $available_services )
2484                        );
2485                }
2486
2487                /**
2488                 * Filters the second paragraph of the health check's description
2489                 * when suggesting the use of a persistent object cache.
2490                 *
2491                 * Hosts may want to replace the notes to recommend their preferred object caching solution.
2492                 *
2493                 * Plugin authors may want to append notes (not replace) on why object caching is recommended for their plugin.
2494                 *
2495                 * @since 6.1.0
2496                 *
2497                 * @param string   $notes              The notes appended to the health check description.
2498                 * @param string[] $available_services The list of available persistent object cache services.
2499                 */
2500                $notes = apply_filters( 'site_status_persistent_object_cache_notes', $notes, $available_services );
2501
2502                $result['status']       = 'recommended';
2503                $result['label']        = __( 'You should use a persistent object cache' );
2504                $result['description'] .= sprintf(
2505                        '<p>%s</p>',
2506                        wp_kses(
2507                                $notes,
2508                                array(
2509                                        'a'      => array( 'href' => true ),
2510                                        'code'   => true,
2511                                        'em'     => true,
2512                                        'strong' => true,
2513                                )
2514                        )
2515                );
2516
2517                return $result;
2518        }
2519
2520        /**
2521         * Returns a set of tests that belong to the site status page.
2522         *
2523         * Each site status test is defined here, they may be `direct` tests, that run on page load, or `async` tests
2524         * which will run later down the line via JavaScript calls to improve page performance and hopefully also user
2525         * experiences.
2526         *
2527         * @since 5.2.0
2528         * @since 5.6.0 Added support for `has_rest` and `permissions`.
2529         *
2530         * @return array The list of tests to run.
2531         */
2532        public static function get_tests() {
2533                $tests = array(
2534                        'direct' => array(
2535                                'wordpress_version'         => array(
2536                                        'label' => __( 'WordPress Version' ),
2537                                        'test'  => 'wordpress_version',
2538                                ),
2539                                'plugin_version'            => array(
2540                                        'label' => __( 'Plugin Versions' ),
2541                                        'test'  => 'plugin_version',
2542                                ),
2543                                'theme_version'             => array(
2544                                        'label' => __( 'Theme Versions' ),
2545                                        'test'  => 'theme_version',
2546                                ),
2547                                'php_version'               => array(
2548                                        'label' => __( 'PHP Version' ),
2549                                        'test'  => 'php_version',
2550                                ),
2551                                'php_extensions'            => array(
2552                                        'label' => __( 'PHP Extensions' ),
2553                                        'test'  => 'php_extensions',
2554                                ),
2555                                'php_default_timezone'      => array(
2556                                        'label' => __( 'PHP Default Timezone' ),
2557                                        'test'  => 'php_default_timezone',
2558                                ),
2559                                'php_sessions'              => array(
2560                                        'label' => __( 'PHP Sessions' ),
2561                                        'test'  => 'php_sessions',
2562                                ),
2563                                'sql_server'                => array(
2564                                        'label' => __( 'Database Server version' ),
2565                                        'test'  => 'sql_server',
2566                                ),
2567                                'utf8mb4_support'           => array(
2568                                        'label' => __( 'MySQL utf8mb4 support' ),
2569                                        'test'  => 'utf8mb4_support',
2570                                ),
2571                                'ssl_support'               => array(
2572                                        'label' => __( 'Secure communication' ),
2573                                        'test'  => 'ssl_support',
2574                                ),
2575                                'scheduled_events'          => array(
2576                                        'label' => __( 'Scheduled events' ),
2577                                        'test'  => 'scheduled_events',
2578                                ),
2579                                'http_requests'             => array(
2580                                        'label' => __( 'HTTP Requests' ),
2581                                        'test'  => 'http_requests',
2582                                ),
2583                                'rest_availability'         => array(
2584                                        'label'     => __( 'REST API availability' ),
2585                                        'test'      => 'rest_availability',
2586                                        'skip_cron' => true,
2587                                ),
2588                                'debug_enabled'             => array(
2589                                        'label' => __( 'Debugging enabled' ),
2590                                        'test'  => 'is_in_debug_mode',
2591                                ),
2592                                'file_uploads'              => array(
2593                                        'label' => __( 'File uploads' ),
2594                                        'test'  => 'file_uploads',
2595                                ),
2596                                'plugin_theme_auto_updates' => array(
2597                                        'label' => __( 'Plugin and theme auto-updates' ),
2598                                        'test'  => 'plugin_theme_auto_updates',
2599                                ),
2600                        ),
2601                        'async'  => array(
2602                                'dotorg_communication' => array(
2603                                        'label'             => __( 'Communication with WordPress.org' ),
2604                                        'test'              => rest_url( 'wp-site-health/v1/tests/dotorg-communication' ),
2605                                        'has_rest'          => true,
2606                                        'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_dotorg_communication' ),
2607                                ),
2608                                'background_updates'   => array(
2609                                        'label'             => __( 'Background updates' ),
2610                                        'test'              => rest_url( 'wp-site-health/v1/tests/background-updates' ),
2611                                        'has_rest'          => true,
2612                                        'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_background_updates' ),
2613                                ),
2614                                'loopback_requests'    => array(
2615                                        'label'             => __( 'Loopback request' ),
2616                                        'test'              => rest_url( 'wp-site-health/v1/tests/loopback-requests' ),
2617                                        'has_rest'          => true,
2618                                        'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_loopback_requests' ),
2619                                ),
2620                                'https_status'         => array(
2621                                        'label'             => __( 'HTTPS status' ),
2622                                        'test'              => rest_url( 'wp-site-health/v1/tests/https-status' ),
2623                                        'has_rest'          => true,
2624                                        'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_https_status' ),
2625                                ),
2626                        ),
2627                );
2628
2629                // Conditionally include Authorization header test if the site isn't protected by Basic Auth.
2630                if ( ! wp_is_site_protected_by_basic_auth() ) {
2631                        $tests['async']['authorization_header'] = array(
2632                                'label'     => __( 'Authorization header' ),
2633                                'test'      => rest_url( 'wp-site-health/v1/tests/authorization-header' ),
2634                                'has_rest'  => true,
2635                                'headers'   => array( 'Authorization' => 'Basic ' . base64_encode( 'user:pwd' ) ),
2636                                'skip_cron' => true,
2637                        );
2638                }
2639
2640                // Only check for caches in production environments.
2641                if ( 'production' === wp_get_environment_type() ) {
2642                        $tests['async']['page_cache'] = array(
2643                                'label'             => __( 'Page cache' ),
2644                                'test'              => rest_url( 'wp-site-health/v1/tests/page-cache' ),
2645                                'has_rest'          => true,
2646                                'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_page_cache' ),
2647                        );
2648
2649                        $tests['direct']['persistent_object_cache'] = array(
2650                                'label' => __( 'Persistent object cache' ),
2651                                'test'  => 'persistent_object_cache',
2652                        );
2653                }
2654
2655                /**
2656                 * Filters which site status tests are run on a site.
2657                 *
2658                 * The site health is determined by a set of tests based on best practices from
2659                 * both the WordPress Hosting Team and web standards in general.
2660                 *
2661                 * Some sites may not have the same requirements, for example the automatic update
2662                 * checks may be handled by a host, and are therefore disabled in core.
2663                 * Or maybe you want to introduce a new test, is caching enabled/disabled/stale for example.
2664                 *
2665                 * Tests may be added either as direct, or asynchronous ones. Any test that may require some time
2666                 * to complete should run asynchronously, to avoid extended loading periods within wp-admin.
2667                 *
2668                 * @since 5.2.0
2669                 * @since 5.6.0 Added the `async_direct_test` array key for asynchronous tests.
2670                 *              Added the `skip_cron` array key for all tests.
2671                 *
2672                 * @param array[] $tests {
2673                 *     An associative array of direct and asynchronous tests.
2674                 *
2675                 *     @type array[] $direct {
2676                 *         An array of direct tests.
2677                 *
2678                 *         @type array ...$identifier {
2679                 *             `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
2680                 *             prefix test identifiers with their slug to avoid collisions between tests.
2681                 *
2682                 *             @type string   $label     The friendly label to identify the test.
2683                 *             @type callable $test      The callback function that runs the test and returns its result.
2684                 *             @type bool     $skip_cron Whether to skip this test when running as cron.
2685                 *         }
2686                 *     }
2687                 *     @type array[] $async {
2688                 *         An array of asynchronous tests.
2689                 *
2690                 *         @type array ...$identifier {
2691                 *             `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
2692                 *             prefix test identifiers with their slug to avoid collisions between tests.
2693                 *
2694                 *             @type string   $label             The friendly label to identify the test.
2695                 *             @type string   $test              An admin-ajax.php action to be called to perform the test, or
2696                 *                                               if `$has_rest` is true, a URL to a REST API endpoint to perform
2697                 *                                               the test.
2698                 *             @type bool     $has_rest          Whether the `$test` property points to a REST API endpoint.
2699                 *             @type bool     $skip_cron         Whether to skip this test when running as cron.
2700                 *             @type callable $async_direct_test A manner of directly calling the test marked as asynchronous,
2701                 *                                               as the scheduled event can not authenticate, and endpoints
2702                 *                                               may require authentication.
2703                 *         }
2704                 *     }
2705                 * }
2706                 */
2707                $tests = apply_filters( 'site_status_tests', $tests );
2708
2709                // Ensure that the filtered tests contain the required array keys.
2710                $tests = array_merge(
2711                        array(
2712                                'direct' => array(),
2713                                'async'  => array(),
2714                        ),
2715                        $tests
2716                );
2717
2718                return $tests;
2719        }
2720
2721        /**
2722         * Adds a class to the body HTML tag.
2723         *
2724         * Filters the body class string for admin pages and adds our own class for easier styling.
2725         *
2726         * @since 5.2.0
2727         *
2728         * @param string $body_class The body class string.
2729         * @return string The modified body class string.
2730         */
2731        public function admin_body_class( $body_class ) {
2732                $screen = get_current_screen();
2733                if ( 'site-health' !== $screen->id ) {
2734                        return $body_class;
2735                }
2736
2737                $body_class .= ' site-health';
2738
2739                return $body_class;
2740        }
2741
2742        /**
2743         * Initiates the WP_Cron schedule test cases.
2744         *
2745         * @since 5.2.0
2746         */
2747        private function wp_schedule_test_init() {
2748                $this->schedules = wp_get_schedules();
2749                $this->get_cron_tasks();
2750        }
2751
2752        /**
2753         * Populates the list of cron events and store them to a class-wide variable.
2754         *
2755         * @since 5.2.0
2756         */
2757        private function get_cron_tasks() {
2758                $cron_tasks = _get_cron_array();
2759
2760                if ( empty( $cron_tasks ) ) {
2761                        $this->crons = new WP_Error( 'no_tasks', __( 'No scheduled events exist on this site.' ) );
2762                        return;
2763                }
2764
2765                $this->crons = array();
2766
2767                foreach ( $cron_tasks as $time => $cron ) {
2768                        foreach ( $cron as $hook => $dings ) {
2769                                foreach ( $dings as $sig => $data ) {
2770
2771                                        $this->crons[ "$hook-$sig-$time" ] = (object) array(
2772                                                'hook'     => $hook,
2773                                                'time'     => $time,
2774                                                'sig'      => $sig,
2775                                                'args'     => $data['args'],
2776                                                'schedule' => $data['schedule'],
2777                                                'interval' => isset( $data['interval'] ) ? $data['interval'] : null,
2778                                        );
2779
2780                                }
2781                        }
2782                }
2783        }
2784
2785        /**
2786         * Checks if any scheduled tasks have been missed.
2787         *
2788         * Returns a boolean value of `true` if a scheduled task has been missed and ends processing.
2789         *
2790         * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value.
2791         *
2792         * @since 5.2.0
2793         *
2794         * @return bool|WP_Error True if a cron was missed, false if not. WP_Error if the cron is set to that.
2795         */
2796        public function has_missed_cron() {
2797                if ( is_wp_error( $this->crons ) ) {
2798                        return $this->crons;
2799                }
2800
2801                foreach ( $this->crons as $id => $cron ) {
2802                        if ( ( (int) $cron->time - time() ) < $this->timeout_missed_cron ) {
2803                                $this->last_missed_cron = $cron->hook;
2804                                return true;
2805                        }
2806                }
2807
2808                return false;
2809        }
2810
2811        /**
2812         * Checks if any scheduled tasks are late.
2813         *
2814         * Returns a boolean value of `true` if a scheduled task is late and ends processing.
2815         *
2816         * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value.
2817         *
2818         * @since 5.3.0
2819         *
2820         * @return bool|WP_Error True if a cron is late, false if not. WP_Error if the cron is set to that.
2821         */
2822        public function has_late_cron() {
2823                if ( is_wp_error( $this->crons ) ) {
2824                        return $this->crons;
2825                }
2826
2827                foreach ( $this->crons as $id => $cron ) {
2828                        $cron_offset = (int) $cron->time - time();
2829                        if (
2830                                $cron_offset >= $this->timeout_missed_cron &&
2831                                $cron_offset < $this->timeout_late_cron
2832                        ) {
2833                                $this->last_late_cron = $cron->hook;
2834                                return true;
2835                        }
2836                }
2837
2838                return false;
2839        }
2840
2841        /**
2842         * Checks for potential issues with plugin and theme auto-updates.
2843         *
2844         * Though there is no way to 100% determine if plugin and theme auto-updates are configured
2845         * correctly, a few educated guesses could be made to flag any conditions that would
2846         * potentially cause unexpected behaviors.
2847         *
2848         * @since 5.5.0
2849         *
2850         * @return object The test results.
2851         */
2852        public function detect_plugin_theme_auto_update_issues() {
2853                $mock_plugin = (object) array(
2854                        'id'            => 'w.org/plugins/a-fake-plugin',
2855                        'slug'          => 'a-fake-plugin',
2856                        'plugin'        => 'a-fake-plugin/a-fake-plugin.php',
2857                        'new_version'   => '9.9',
2858                        'url'           => 'https://wordpress.org/plugins/a-fake-plugin/',
2859                        'package'       => 'https://downloads.wordpress.org/plugin/a-fake-plugin.9.9.zip',
2860                        'icons'         => array(
2861                                '2x' => 'https://ps.w.org/a-fake-plugin/assets/icon-256x256.png',
2862                                '1x' => 'https://ps.w.org/a-fake-plugin/assets/icon-128x128.png',
2863                        ),
2864                        'banners'       => array(
2865                                '2x' => 'https://ps.w.org/a-fake-plugin/assets/banner-1544x500.png',
2866                                '1x' => 'https://ps.w.org/a-fake-plugin/assets/banner-772x250.png',
2867                        ),
2868                        'banners_rtl'   => array(),
2869                        'tested'        => '5.5.0',
2870                        'requires_php'  => '5.6.20',
2871                        'compatibility' => new stdClass(),
2872                );
2873
2874                $mock_theme = (object) array(
2875                        'theme'        => 'a-fake-theme',
2876                        'new_version'  => '9.9',
2877                        'url'          => 'https://wordpress.org/themes/a-fake-theme/',
2878                        'package'      => 'https://downloads.wordpress.org/theme/a-fake-theme.9.9.zip',
2879                        'requires'     => '5.0.0',
2880                        'requires_php' => '5.6.20',
2881                );
2882
2883                $test_plugins_enabled = wp_is_auto_update_forced_for_item( 'plugin', true, $mock_plugin );
2884                $test_themes_enabled  = wp_is_auto_update_forced_for_item( 'theme', true, $mock_theme );
2885
2886                $ui_enabled_for_plugins = wp_is_auto_update_enabled_for_type( 'plugin' );
2887                $ui_enabled_for_themes  = wp_is_auto_update_enabled_for_type( 'theme' );
2888                $plugin_filter_present  = has_filter( 'auto_update_plugin' );
2889                $theme_filter_present   = has_filter( 'auto_update_theme' );
2890
2891                if ( ( ! $test_plugins_enabled && $ui_enabled_for_plugins )
2892                        || ( ! $test_themes_enabled && $ui_enabled_for_themes )
2893                ) {
2894                        return (object) array(
2895                                'status'  => 'critical',
2896                                'message' => __( 'Auto-updates for plugins and/or themes appear to be disabled, but settings are still set to be displayed. This could cause auto-updates to not work as expected.' ),
2897                        );
2898                }
2899
2900                if ( ( ! $test_plugins_enabled && $plugin_filter_present )
2901                        && ( ! $test_themes_enabled && $theme_filter_present )
2902                ) {
2903                        return (object) array(
2904                                'status'  => 'recommended',
2905                                'message' => __( 'Auto-updates for plugins and themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
2906                        );
2907                } elseif ( ! $test_plugins_enabled && $plugin_filter_present ) {
2908                        return (object) array(
2909                                'status'  => 'recommended',
2910                                'message' => __( 'Auto-updates for plugins appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
2911                        );
2912                } elseif ( ! $test_themes_enabled && $theme_filter_present ) {
2913                        return (object) array(
2914                                'status'  => 'recommended',
2915                                'message' => __( 'Auto-updates for themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
2916                        );
2917                }
2918
2919                return (object) array(
2920                        'status'  => 'good',
2921                        'message' => __( 'There appear to be no issues with plugin and theme auto-updates.' ),
2922                );
2923        }
2924
2925        /**
2926         * Runs a loopback test on the site.
2927         *
2928         * Loopbacks are what WordPress uses to communicate with itself to start up WP_Cron, scheduled posts,
2929         * make sure plugin or theme edits don't cause site failures and similar.
2930         *
2931         * @since 5.2.0
2932         *
2933         * @return object The test results.
2934         */
2935        public function can_perform_loopback() {
2936                $body    = array( 'site-health' => 'loopback-test' );
2937                $cookies = wp_unslash( $_COOKIE );
2938                $timeout = 10; // 10 seconds.
2939                $headers = array(
2940                        'Cache-Control' => 'no-cache',
2941                );
2942                /** This filter is documented in wp-includes/class-wp-http-streams.php */
2943                $sslverify = apply_filters( 'https_local_ssl_verify', false );
2944
2945                // Include Basic auth in loopback requests.
2946                if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
2947                        $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
2948                }
2949
2950                $url = site_url( 'wp-cron.php' );
2951
2952                /*
2953                 * A post request is used for the wp-cron.php loopback test to cause the file
2954                 * to finish early without triggering cron jobs. This has two benefits:
2955                 * - cron jobs are not triggered a second time on the site health page,
2956                 * - the loopback request finishes sooner providing a quicker result.
2957                 *
2958                 * Using a POST request causes the loopback to differ slightly to the standard
2959                 * GET request WordPress uses for wp-cron.php loopback requests but is close
2960                 * enough. See https://core.trac.wordpress.org/ticket/52547
2961                 */
2962                $r = wp_remote_post( $url, compact( 'body', 'cookies', 'headers', 'timeout', 'sslverify' ) );
2963
2964                if ( is_wp_error( $r ) ) {
2965                        return (object) array(
2966                                'status'  => 'critical',
2967                                'message' => sprintf(
2968                                        '%s<br>%s',
2969                                        __( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ),
2970                                        sprintf(
2971                                                /* translators: 1: The WordPress error message. 2: The WordPress error code. */
2972                                                __( 'Error: %1$s (%2$s)' ),
2973                                                $r->get_error_message(),
2974                                                $r->get_error_code()
2975                                        )
2976                                ),
2977                        );
2978                }
2979
2980                if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
2981                        return (object) array(
2982                                'status'  => 'recommended',
2983                                'message' => sprintf(
2984                                        /* translators: %d: The HTTP response code returned. */
2985                                        __( 'The loopback request returned an unexpected http status code, %d, it was not possible to determine if this will prevent features from working as expected.' ),
2986                                        wp_remote_retrieve_response_code( $r )
2987                                ),
2988                        );
2989                }
2990
2991                return (object) array(
2992                        'status'  => 'good',
2993                        'message' => __( 'The loopback request to your site completed successfully.' ),
2994                );
2995        }
2996
2997        /**
2998         * Creates a weekly cron event, if one does not already exist.
2999         *
3000         * @since 5.4.0
3001         */
3002        public function maybe_create_scheduled_event() {
3003                if ( ! wp_next_scheduled( 'wp_site_health_scheduled_check' ) && ! wp_installing() ) {
3004                        wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', 'wp_site_health_scheduled_check' );
3005                }
3006        }
3007
3008        /**
3009         * Runs the scheduled event to check and update the latest site health status for the website.
3010         *
3011         * @since 5.4.0
3012         */
3013        public function wp_cron_scheduled_check() {
3014                // Bootstrap wp-admin, as WP_Cron doesn't do this for us.
3015                require_once trailingslashit( ABSPATH ) . 'wp-admin/includes/admin.php';
3016
3017                $tests = WP_Site_Health::get_tests();
3018
3019                $results = array();
3020
3021                $site_status = array(
3022                        'good'        => 0,
3023                        'recommended' => 0,
3024                        'critical'    => 0,
3025                );
3026
3027                // Don't run https test on development environments.
3028                if ( $this->is_development_environment() ) {
3029                        unset( $tests['async']['https_status'] );
3030                }
3031
3032                foreach ( $tests['direct'] as $test ) {
3033                        if ( ! empty( $test['skip_cron'] ) ) {
3034                                continue;
3035                        }
3036
3037                        if ( is_string( $test['test'] ) ) {
3038                                $test_function = sprintf(
3039                                        'get_test_%s',
3040                                        $test['test']
3041                                );
3042
3043                                if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
3044                                        $results[] = $this->perform_test( array( $this, $test_function ) );
3045                                        continue;
3046                                }
3047                        }
3048
3049                        if ( is_callable( $test['test'] ) ) {
3050                                $results[] = $this->perform_test( $test['test'] );
3051                        }
3052                }
3053
3054                foreach ( $tests['async'] as $test ) {
3055                        if ( ! empty( $test['skip_cron'] ) ) {
3056                                continue;
3057                        }
3058
3059                        // Local endpoints may require authentication, so asynchronous tests can pass a direct test runner as well.
3060                        if ( ! empty( $test['async_direct_test'] ) && is_callable( $test['async_direct_test'] ) ) {
3061                                // This test is callable, do so and continue to the next asynchronous check.
3062                                $results[] = $this->perform_test( $test['async_direct_test'] );
3063                                continue;
3064                        }
3065
3066                        if ( is_string( $test['test'] ) ) {
3067                                // Check if this test has a REST API endpoint.
3068                                if ( isset( $test['has_rest'] ) && $test['has_rest'] ) {
3069                                        $result_fetch = wp_remote_get(
3070                                                $test['test'],
3071                                                array(
3072                                                        'body' => array(
3073                                                                '_wpnonce' => wp_create_nonce( 'wp_rest' ),
3074                                                        ),
3075                                                )
3076                                        );
3077                                } else {
3078                                        $result_fetch = wp_remote_post(
3079                                                admin_url( 'admin-ajax.php' ),
3080                                                array(
3081                                                        'body' => array(
3082                                                                'action'   => $test['test'],
3083                                                                '_wpnonce' => wp_create_nonce( 'health-check-site-status' ),
3084                                                        ),
3085                                                )
3086                                        );
3087                                }
3088
3089                                if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) {
3090                                        $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true );
3091                                } else {
3092                                        $result = false;
3093                                }
3094
3095                                if ( is_array( $result ) ) {
3096                                        $results[] = $result;
3097                                } else {
3098                                        $results[] = array(
3099                                                'status' => 'recommended',
3100                                                'label'  => __( 'A test is unavailable' ),
3101                                        );
3102                                }
3103                        }
3104                }
3105
3106                foreach ( $results as $result ) {
3107                        if ( 'critical' === $result['status'] ) {
3108                                $site_status['critical']++;
3109                        } elseif ( 'recommended' === $result['status'] ) {
3110                                $site_status['recommended']++;
3111                        } else {
3112                                $site_status['good']++;
3113                        }
3114                }
3115
3116                set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) );
3117        }
3118
3119        /**
3120         * Checks if the current environment type is set to 'development' or 'local'.
3121         *
3122         * @since 5.6.0
3123         *
3124         * @return bool True if it is a development environment, false if not.
3125         */
3126        public function is_development_environment() {
3127                return in_array( wp_get_environment_type(), array( 'development', 'local' ), true );
3128        }
3129
3130        /**
3131         * Returns a list of headers and its verification callback to verify if page cache is enabled or not.
3132         *
3133         * Note: key is header name and value could be callable function to verify header value.
3134         * Empty value mean existence of header detect page cache is enabled.
3135         *
3136         * @since 6.1.0
3137         *
3138         * @return array List of client caching headers and their (optional) verification callbacks.
3139         */
3140        public function get_page_cache_headers() {
3141
3142                $cache_hit_callback = static function ( $header_value ) {
3143                        return false !== strpos( strtolower( $header_value ), 'hit' );
3144                };
3145
3146                $cache_headers = array(
3147                        'cache-control'          => static function ( $header_value ) {
3148                                return (bool) preg_match( '/max-age=[1-9]/', $header_value );
3149                        },
3150                        'expires'                => static function ( $header_value ) {
3151                                return strtotime( $header_value ) > time();
3152                        },
3153                        'age'                    => static function ( $header_value ) {
3154                                return is_numeric( $header_value ) && $header_value > 0;
3155                        },
3156                        'last-modified'          => '',
3157                        'etag'                   => '',
3158                        'x-cache-enabled'        => static function ( $header_value ) {
3159                                return 'true' === strtolower( $header_value );
3160                        },
3161                        'x-cache-disabled'       => static function ( $header_value ) {
3162                                return ( 'on' !== strtolower( $header_value ) );
3163                        },
3164                        'x-srcache-store-status' => $cache_hit_callback,
3165                        'x-srcache-fetch-status' => $cache_hit_callback,
3166                );
3167
3168                /**
3169                 * Filters the list of cache headers supported by core.
3170                 *
3171                 * @since 6.1.0
3172                 *
3173                 * @param array $cache_headers Array of supported cache headers.
3174                 */
3175                return apply_filters( 'site_status_page_cache_supported_cache_headers', $cache_headers );
3176        }
3177
3178        /**
3179         * Checks if site has page cache enabled or not.
3180         *
3181         * @since 6.1.0
3182         *
3183         * @return WP_Error|array {
3184         *     Page cache detection details or else error information.
3185         *
3186         *     @type bool    $advanced_cache_present        Whether a page cache plugin is present.
3187         *     @type array[] $page_caching_response_headers Sets of client caching headers for the responses.
3188         *     @type float[] $response_timing               Response timings.
3189         * }
3190         */
3191        private function check_for_page_caching() {
3192
3193                /** This filter is documented in wp-includes/class-wp-http-streams.php */
3194                $sslverify = apply_filters( 'https_local_ssl_verify', false );
3195
3196                $headers = array();
3197
3198                // Include basic auth in loopback requests. Note that this will only pass along basic auth when user is
3199                // initiating the test. If a site requires basic auth, the test will fail when it runs in WP Cron as part of
3200                // wp_site_health_scheduled_check. This logic is copied from WP_Site_Health::can_perform_loopback().
3201                if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
3202                        $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
3203                }
3204
3205                $caching_headers               = $this->get_page_cache_headers();
3206                $page_caching_response_headers = array();
3207                $response_timing               = array();
3208
3209                for ( $i = 1; $i <= 3; $i++ ) {
3210                        $start_time    = microtime( true );
3211                        $http_response = wp_remote_get( home_url( '/' ), compact( 'sslverify', 'headers' ) );
3212                        $end_time      = microtime( true );
3213
3214                        if ( is_wp_error( $http_response ) ) {
3215                                return $http_response;
3216                        }
3217                        if ( wp_remote_retrieve_response_code( $http_response ) !== 200 ) {
3218                                return new WP_Error(
3219                                        'http_' . wp_remote_retrieve_response_code( $http_response ),
3220                                        wp_remote_retrieve_response_message( $http_response )
3221                                );
3222                        }
3223
3224                        $response_headers = array();
3225
3226                        foreach ( $caching_headers as $header => $callback ) {
3227                                $header_values = wp_remote_retrieve_header( $http_response, $header );
3228                                if ( empty( $header_values ) ) {
3229                                        continue;
3230                                }
3231                                $header_values = (array) $header_values;
3232                                if ( empty( $callback ) || ( is_callable( $callback ) && count( array_filter( $header_values, $callback ) ) > 0 ) ) {
3233                                        $response_headers[ $header ] = $header_values;
3234                                }
3235                        }
3236
3237                        $page_caching_response_headers[] = $response_headers;
3238                        $response_timing[]               = ( $end_time - $start_time ) * 1000;
3239                }
3240
3241                return array(
3242                        'advanced_cache_present'        => (
3243                                file_exists( WP_CONTENT_DIR . '/advanced-cache.php' )
3244                                &&
3245                                ( defined( 'WP_CACHE' ) && WP_CACHE )
3246                                &&
3247                                /** This filter is documented in wp-settings.php */
3248                                apply_filters( 'enable_loading_advanced_cache_dropin', true )
3249                        ),
3250                        'page_caching_response_headers' => $page_caching_response_headers,
3251                        'response_timing'               => $response_timing,
3252                );
3253        }
3254
3255        /**
3256         * Gets page cache details.
3257         *
3258         * @since 6.1.0
3259         *
3260         * @return WP_Error|array {
3261         *    Page cache detail or else a WP_Error if unable to determine.
3262         *
3263         *    @type string   $status                 Page cache status. Good, Recommended or Critical.
3264         *    @type bool     $advanced_cache_present Whether page cache plugin is available or not.
3265         *    @type string[] $headers                Client caching response headers detected.
3266         *    @type float    $response_time          Response time of site.
3267         * }
3268         */
3269        private function get_page_cache_detail() {
3270                $page_cache_detail = $this->check_for_page_caching();
3271                if ( is_wp_error( $page_cache_detail ) ) {
3272                        return $page_cache_detail;
3273                }
3274
3275                // Use the median server response time.
3276                $response_timings = $page_cache_detail['response_timing'];
3277                rsort( $response_timings );
3278                $page_speed = $response_timings[ floor( count( $response_timings ) / 2 ) ];
3279
3280                // Obtain unique set of all client caching response headers.
3281                $headers = array();
3282                foreach ( $page_cache_detail['page_caching_response_headers'] as $page_caching_response_headers ) {
3283                        $headers = array_merge( $headers, array_keys( $page_caching_response_headers ) );
3284                }
3285                $headers = array_unique( $headers );
3286
3287                // Page cache is detected if there are response headers or a page cache plugin is present.
3288                $has_page_caching = ( count( $headers ) > 0 || $page_cache_detail['advanced_cache_present'] );
3289
3290                if ( $page_speed && $page_speed < $this->get_good_response_time_threshold() ) {
3291                        $result = $has_page_caching ? 'good' : 'recommended';
3292                } else {
3293                        $result = 'critical';
3294                }
3295
3296                return array(
3297                        'status'                 => $result,
3298                        'advanced_cache_present' => $page_cache_detail['advanced_cache_present'],
3299                        'headers'                => $headers,
3300                        'response_time'          => $page_speed,
3301                );
3302        }
3303
3304        /**
3305         * Gets the threshold below which a response time is considered good.
3306         *
3307         * @since 6.1.0
3308         *
3309         * @return int Threshold in milliseconds.
3310         */
3311        private function get_good_response_time_threshold() {
3312                /**
3313                 * Filters the threshold below which a response time is considered good.
3314                 *
3315                 * The default is based on https://web.dev/time-to-first-byte/.
3316                 *
3317                 * @param int $threshold Threshold in milliseconds. Default 600.
3318                 *
3319                 * @since 6.1.0
3320                 */
3321                return (int) apply_filters( 'site_status_good_response_time_threshold', 600 );
3322        }
3323
3324        /**
3325         * Determines whether to suggest using a persistent object cache.
3326         *
3327         * @since 6.1.0
3328         *
3329         * @global wpdb $wpdb WordPress database abstraction object.
3330         *
3331         * @return bool Whether to suggest using a persistent object cache.
3332         */
3333        public function should_suggest_persistent_object_cache() {
3334                global $wpdb;
3335
3336                /**
3337                 * Filters whether to suggest use of a persistent object cache and bypass default threshold checks.
3338                 *
3339                 * Using this filter allows to override the default logic, effectively short-circuiting the method.
3340                 *
3341                 * @since 6.1.0
3342                 *
3343                 * @param bool|null $suggest Boolean to short-circuit, for whether to suggest using a persistent object cache.
3344                 *                           Default null.
3345                 */
3346                $short_circuit = apply_filters( 'site_status_should_suggest_persistent_object_cache', null );
3347                if ( is_bool( $short_circuit ) ) {
3348                        return $short_circuit;
3349                }
3350
3351                if ( is_multisite() ) {
3352                        return true;
3353                }
3354
3355                /**
3356                 * Filters the thresholds used to determine whether to suggest the use of a persistent object cache.
3357                 *
3358                 * @since 6.1.0
3359                 *
3360                 * @param int[] $thresholds The list of threshold numbers keyed by threshold name.
3361                 */
3362                $thresholds = apply_filters(
3363                        'site_status_persistent_object_cache_thresholds',
3364                        array(
3365                                'alloptions_count' => 500,
3366                                'alloptions_bytes' => 100000,
3367                                'comments_count'   => 1000,
3368                                'options_count'    => 1000,
3369                                'posts_count'      => 1000,
3370                                'terms_count'      => 1000,
3371                                'users_count'      => 1000,
3372                        )
3373                );
3374
3375                $alloptions = wp_load_alloptions();
3376
3377                if ( $thresholds['alloptions_count'] < count( $alloptions ) ) {
3378                        return true;
3379                }
3380
3381                if ( $thresholds['alloptions_bytes'] < strlen( serialize( $alloptions ) ) ) {
3382                        return true;
3383                }
3384
3385                $table_names = implode( "','", array( $wpdb->comments, $wpdb->options, $wpdb->posts, $wpdb->terms, $wpdb->users ) );
3386
3387                // With InnoDB the `TABLE_ROWS` are estimates, which are accurate enough and faster to retrieve than individual `COUNT()` queries.
3388                $results = $wpdb->get_results(
3389                        $wpdb->prepare(
3390                                // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- This query cannot use interpolation.
3391                                "SELECT TABLE_NAME AS 'table', TABLE_ROWS AS 'rows', SUM(data_length + index_length) as 'bytes' FROM information_schema.TABLES WHERE TABLE_SCHEMA = %s AND TABLE_NAME IN ('$table_names') GROUP BY TABLE_NAME;",
3392                                DB_NAME
3393                        ),
3394                        OBJECT_K
3395                );
3396
3397                $threshold_map = array(
3398                        'comments_count' => $wpdb->comments,
3399                        'options_count'  => $wpdb->options,
3400                        'posts_count'    => $wpdb->posts,
3401                        'terms_count'    => $wpdb->terms,
3402                        'users_count'    => $wpdb->users,
3403                );
3404
3405                foreach ( $threshold_map as $threshold => $table ) {
3406                        if ( $thresholds[ $threshold ] <= $results[ $table ]->rows ) {
3407                                return true;
3408                        }
3409                }
3410
3411                return false;
3412        }
3413
3414        /**
3415         * Returns a list of available persistent object cache services.
3416         *
3417         * @since 6.1.0
3418         *
3419         * @return string[] The list of available persistent object cache services.
3420         */
3421        private function available_object_cache_services() {
3422                $extensions = array_map(
3423                        'extension_loaded',
3424                        array(
3425                                'APCu'      => 'apcu',
3426                                'Redis'     => 'redis',
3427                                'Relay'     => 'relay',
3428                                'Memcache'  => 'memcache',
3429                                'Memcached' => 'memcached',
3430                        )
3431                );
3432
3433                $services = array_keys( array_filter( $extensions ) );
3434
3435                /**
3436                 * Filters the persistent object cache services available to the user.
3437                 *
3438                 * This can be useful to hide or add services not included in the defaults.
3439                 *
3440                 * @since 6.1.0
3441                 *
3442                 * @param string[] $services The list of available persistent object cache services.
3443                 */
3444                return apply_filters( 'site_status_available_object_cache_services', $services );
3445        }
3446
3447}