[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-admin/includes/ -> class-wp-site-health.php (source)

   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  class WP_Site_Health {
  11      private static $instance = null;
  12  
  13      private $mysql_min_version_check;
  14      private $mysql_rec_version_check;
  15  
  16      public $is_mariadb                           = false;
  17      private $mysql_server_version                = '';
  18      private $health_check_mysql_required_version = '5.5';
  19      private $health_check_mysql_rec_version      = '';
  20  
  21      public $schedules;
  22      public $crons;
  23      public $last_missed_cron     = null;
  24      public $last_late_cron       = null;
  25      private $timeout_missed_cron = null;
  26      private $timeout_late_cron   = null;
  27  
  28      /**
  29       * WP_Site_Health constructor.
  30       *
  31       * @since 5.2.0
  32       */
  33  	public function __construct() {
  34          $this->maybe_create_scheduled_event();
  35  
  36          $this->prepare_sql_data();
  37  
  38          $this->timeout_late_cron   = 0;
  39          $this->timeout_missed_cron = - 5 * MINUTE_IN_SECONDS;
  40  
  41          if ( defined( 'DISABLE_WP_CRON' ) && DISABLE_WP_CRON ) {
  42              $this->timeout_late_cron   = - 15 * MINUTE_IN_SECONDS;
  43              $this->timeout_missed_cron = - 1 * HOUR_IN_SECONDS;
  44          }
  45  
  46          add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
  47  
  48          add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
  49          add_action( 'wp_site_health_scheduled_check', array( $this, 'wp_cron_scheduled_check' ) );
  50      }
  51  
  52      /**
  53       * Return an instance of the WP_Site_Health class, or create one if none exist yet.
  54       *
  55       * @since 5.4.0
  56       *
  57       * @return WP_Site_Health|null
  58       */
  59  	public static function initialize() {
  60          if ( null === self::$instance ) {
  61              self::$instance = new WP_Site_Health();
  62          }
  63  
  64          return self::$instance;
  65      }
  66  
  67      /**
  68       * Enqueues the site health scripts.
  69       *
  70       * @since 5.2.0
  71       */
  72  	public function enqueue_scripts() {
  73          $screen = get_current_screen();
  74          if ( 'site-health' !== $screen->id && 'dashboard' !== $screen->id ) {
  75              return;
  76          }
  77  
  78          $health_check_js_variables = array(
  79              'screen'      => $screen->id,
  80              'nonce'       => array(
  81                  'site_status'        => wp_create_nonce( 'health-check-site-status' ),
  82                  'site_status_result' => wp_create_nonce( 'health-check-site-status-result' ),
  83              ),
  84              'site_status' => array(
  85                  'direct' => array(),
  86                  'async'  => array(),
  87                  'issues' => array(
  88                      'good'        => 0,
  89                      'recommended' => 0,
  90                      'critical'    => 0,
  91                  ),
  92              ),
  93          );
  94  
  95          $issue_counts = get_transient( 'health-check-site-status-result' );
  96  
  97          if ( false !== $issue_counts ) {
  98              $issue_counts = json_decode( $issue_counts );
  99  
 100              $health_check_js_variables['site_status']['issues'] = $issue_counts;
 101          }
 102  
 103          if ( 'site-health' === $screen->id && ! isset( $_GET['tab'] ) ) {
 104              $tests = WP_Site_Health::get_tests();
 105  
 106              // Don't run https test on localhost
 107              if ( 'localhost' === preg_replace( '|https?://|', '', get_site_url() ) ) {
 108                  unset( $tests['direct']['https_status'] );
 109              }
 110  
 111              foreach ( $tests['direct'] as $test ) {
 112                  if ( is_string( $test['test'] ) ) {
 113                      $test_function = sprintf(
 114                          'get_test_%s',
 115                          $test['test']
 116                      );
 117  
 118                      if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
 119                          $health_check_js_variables['site_status']['direct'][] = $this->perform_test( array( $this, $test_function ) );
 120                          continue;
 121                      }
 122                  }
 123  
 124                  if ( is_callable( $test['test'] ) ) {
 125                      $health_check_js_variables['site_status']['direct'][] = $this->perform_test( $test['test'] );
 126                  }
 127              }
 128  
 129              foreach ( $tests['async'] as $test ) {
 130                  if ( is_string( $test['test'] ) ) {
 131                      $health_check_js_variables['site_status']['async'][] = array(
 132                          'test'      => $test['test'],
 133                          'completed' => false,
 134                      );
 135                  }
 136              }
 137          }
 138  
 139          wp_localize_script( 'site-health', 'SiteHealth', $health_check_js_variables );
 140      }
 141  
 142      /**
 143       * Run a Site Health test directly.
 144       *
 145       * @since 5.4.0
 146       *
 147       * @param $callback
 148       *
 149       * @return mixed|void
 150       */
 151  	private function perform_test( $callback ) {
 152          /**
 153           * Filter the output of a finished Site Health test.
 154           *
 155           * @since 5.3.0
 156           *
 157           * @param array $test_result {
 158           *     An associated array of test result data.
 159           *
 160           *     @param string $label  A label describing the test, and is used as a header in the output.
 161           *     @param string $status The status of the test, which can be a value of `good`, `recommended` or `critical`.
 162           *     @param array  $badge {
 163           *         Tests are put into categories which have an associated badge shown, these can be modified and assigned here.
 164           *
 165           *         @param string $label The test label, for example `Performance`.
 166           *         @param string $color Default `blue`. A string representing a color to use for the label.
 167           *     }
 168           *     @param string $description A more descriptive explanation of what the test looks for, and why it is important for the end user.
 169           *     @param string $actions     An action to direct the user to where they can resolve the issue, if one exists.
 170           *     @param string $test        The name of the test being ran, used as a reference point.
 171           * }
 172           */
 173          return apply_filters( 'site_status_test_result', call_user_func( $callback ) );
 174      }
 175  
 176      /**
 177       * Run the SQL version checks.
 178       *
 179       * These values are used in later tests, but the part of preparing them is more easily managed early
 180       * in the class for ease of access and discovery.
 181       *
 182       * @since 5.2.0
 183       *
 184       * @global wpdb $wpdb WordPress database abstraction object.
 185       */
 186  	private function prepare_sql_data() {
 187          global $wpdb;
 188  
 189          if ( $wpdb->use_mysqli ) {
 190              // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysqli_get_server_info
 191              $mysql_server_type = mysqli_get_server_info( $wpdb->dbh );
 192          } else {
 193              // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_get_server_info,PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
 194              $mysql_server_type = mysql_get_server_info( $wpdb->dbh );
 195          }
 196  
 197          $this->mysql_server_version = $wpdb->get_var( 'SELECT VERSION()' );
 198  
 199          $this->health_check_mysql_rec_version = '5.6';
 200  
 201          if ( stristr( $mysql_server_type, 'mariadb' ) ) {
 202              $this->is_mariadb                     = true;
 203              $this->health_check_mysql_rec_version = '10.0';
 204          }
 205  
 206          $this->mysql_min_version_check = version_compare( '5.5', $this->mysql_server_version, '<=' );
 207          $this->mysql_rec_version_check = version_compare( $this->health_check_mysql_rec_version, $this->mysql_server_version, '<=' );
 208      }
 209  
 210      /**
 211       * Test if `wp_version_check` is blocked.
 212       *
 213       * It's possible to block updates with the `wp_version_check` filter, but this can't be checked during an
 214       * AJAX call, as the filter is never introduced then.
 215       *
 216       * This filter overrides a normal page request if it's made by an admin through the AJAX call with the
 217       * right query argument to check for this.
 218       *
 219       * @since 5.2.0
 220       */
 221  	public function check_wp_version_check_exists() {
 222          if ( ! is_admin() || ! is_user_logged_in() || ! current_user_can( 'update_core' ) || ! isset( $_GET['health-check-test-wp_version_check'] ) ) {
 223              return;
 224          }
 225  
 226          echo ( has_filter( 'wp_version_check', 'wp_version_check' ) ? 'yes' : 'no' );
 227  
 228          die();
 229      }
 230  
 231      /**
 232       * Tests for WordPress version and outputs it.
 233       *
 234       * Gives various results depending on what kind of updates are available, if any, to encourage the
 235       * user to install security updates as a priority.
 236       *
 237       * @since 5.2.0
 238       *
 239       * @return array The test result.
 240       */
 241  	public function get_test_wordpress_version() {
 242          $result = array(
 243              'label'       => '',
 244              'status'      => '',
 245              'badge'       => array(
 246                  'label' => __( 'Performance' ),
 247                  'color' => 'blue',
 248              ),
 249              'description' => '',
 250              'actions'     => '',
 251              'test'        => 'wordpress_version',
 252          );
 253  
 254          $core_current_version = get_bloginfo( 'version' );
 255          $core_updates         = get_core_updates();
 256  
 257          if ( ! is_array( $core_updates ) ) {
 258              $result['status'] = 'recommended';
 259  
 260              $result['label'] = sprintf(
 261                  /* translators: %s: Your current version of WordPress. */
 262                  __( 'WordPress version %s' ),
 263                  $core_current_version
 264              );
 265  
 266              $result['description'] = sprintf(
 267                  '<p>%s</p>',
 268                  __( 'We were unable to check if any new versions of WordPress are available.' )
 269              );
 270  
 271              $result['actions'] = sprintf(
 272                  '<a href="%s">%s</a>',
 273                  esc_url( admin_url( 'update-core.php?force-check=1' ) ),
 274                  __( 'Check for updates manually' )
 275              );
 276          } else {
 277              foreach ( $core_updates as $core => $update ) {
 278                  if ( 'upgrade' === $update->response ) {
 279                      $current_version = explode( '.', $core_current_version );
 280                      $new_version     = explode( '.', $update->version );
 281  
 282                      $current_major = $current_version[0] . '.' . $current_version[1];
 283                      $new_major     = $new_version[0] . '.' . $new_version[1];
 284  
 285                      $result['label'] = sprintf(
 286                          /* translators: %s: The latest version of WordPress available. */
 287                          __( 'WordPress update available (%s)' ),
 288                          $update->version
 289                      );
 290  
 291                      $result['actions'] = sprintf(
 292                          '<a href="%s">%s</a>',
 293                          esc_url( admin_url( 'update-core.php' ) ),
 294                          __( 'Install the latest version of WordPress' )
 295                      );
 296  
 297                      if ( $current_major !== $new_major ) {
 298                          // This is a major version mismatch.
 299                          $result['status']      = 'recommended';
 300                          $result['description'] = sprintf(
 301                              '<p>%s</p>',
 302                              __( 'A new version of WordPress is available.' )
 303                          );
 304                      } else {
 305                          // This is a minor version, sometimes considered more critical.
 306                          $result['status']         = 'critical';
 307                          $result['badge']['label'] = __( 'Security' );
 308                          $result['description']    = sprintf(
 309                              '<p>%s</p>',
 310                              __( 'A new minor update is available for your site. Because minor updates often address security, it&#8217;s important to install them.' )
 311                          );
 312                      }
 313                  } else {
 314                      $result['status'] = 'good';
 315                      $result['label']  = sprintf(
 316                          /* translators: %s: The current version of WordPress installed on this site. */
 317                          __( 'Your version of WordPress (%s) is up to date' ),
 318                          $core_current_version
 319                      );
 320  
 321                      $result['description'] = sprintf(
 322                          '<p>%s</p>',
 323                          __( 'You are currently running the latest version of WordPress available, keep it up!' )
 324                      );
 325                  }
 326              }
 327          }
 328  
 329          return $result;
 330      }
 331  
 332      /**
 333       * Test if plugins are outdated, or unnecessary.
 334       *
 335       * The tests checks if your plugins are up to date, and encourages you to remove any that are not in use.
 336       *
 337       * @since 5.2.0
 338       *
 339       * @return array The test result.
 340       */
 341  	public function get_test_plugin_version() {
 342          $result = array(
 343              'label'       => __( 'Your plugins are all up to date' ),
 344              'status'      => 'good',
 345              'badge'       => array(
 346                  'label' => __( 'Security' ),
 347                  'color' => 'blue',
 348              ),
 349              'description' => sprintf(
 350                  '<p>%s</p>',
 351                  __( '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.' )
 352              ),
 353              'actions'     => sprintf(
 354                  '<p><a href="%s">%s</a></p>',
 355                  esc_url( admin_url( 'plugins.php' ) ),
 356                  __( 'Manage your plugins' )
 357              ),
 358              'test'        => 'plugin_version',
 359          );
 360  
 361          $plugins        = get_plugins();
 362          $plugin_updates = get_plugin_updates();
 363  
 364          $plugins_have_updates = false;
 365          $plugins_active       = 0;
 366          $plugins_total        = 0;
 367          $plugins_need_update  = 0;
 368  
 369          // Loop over the available plugins and check their versions and active state.
 370          foreach ( $plugins as $plugin_path => $plugin ) {
 371              $plugins_total++;
 372  
 373              if ( is_plugin_active( $plugin_path ) ) {
 374                  $plugins_active++;
 375              }
 376  
 377              $plugin_version = $plugin['Version'];
 378  
 379              if ( array_key_exists( $plugin_path, $plugin_updates ) ) {
 380                  $plugins_need_update++;
 381                  $plugins_have_updates = true;
 382              }
 383          }
 384  
 385          // Add a notice if there are outdated plugins.
 386          if ( $plugins_need_update > 0 ) {
 387              $result['status'] = 'critical';
 388  
 389              $result['label'] = __( 'You have plugins waiting to be updated' );
 390  
 391              $result['description'] .= sprintf(
 392                  '<p>%s</p>',
 393                  sprintf(
 394                      /* translators: %d: The number of outdated plugins. */
 395                      _n(
 396                          'Your site has %d plugin waiting to be updated.',
 397                          'Your site has %d plugins waiting to be updated.',
 398                          $plugins_need_update
 399                      ),
 400                      $plugins_need_update
 401                  )
 402              );
 403  
 404              $result['actions'] .= sprintf(
 405                  '<p><a href="%s">%s</a></p>',
 406                  esc_url( network_admin_url( 'plugins.php?plugin_status=upgrade' ) ),
 407                  __( 'Update your plugins' )
 408              );
 409          } else {
 410              if ( 1 === $plugins_active ) {
 411                  $result['description'] .= sprintf(
 412                      '<p>%s</p>',
 413                      __( 'Your site has 1 active plugin, and it is up to date.' )
 414                  );
 415              } else {
 416                  $result['description'] .= sprintf(
 417                      '<p>%s</p>',
 418                      sprintf(
 419                          /* translators: %d: The number of active plugins. */
 420                          _n(
 421                              'Your site has %d active plugin, and it is up to date.',
 422                              'Your site has %d active plugins, and they are all up to date.',
 423                              $plugins_active
 424                          ),
 425                          $plugins_active
 426                      )
 427                  );
 428              }
 429          }
 430  
 431          // Check if there are inactive plugins.
 432          if ( $plugins_total > $plugins_active && ! is_multisite() ) {
 433              $unused_plugins = $plugins_total - $plugins_active;
 434  
 435              $result['status'] = 'recommended';
 436  
 437              $result['label'] = __( 'You should remove inactive plugins' );
 438  
 439              $result['description'] .= sprintf(
 440                  '<p>%s %s</p>',
 441                  sprintf(
 442                      /* translators: %d: The number of inactive plugins. */
 443                      _n(
 444                          'Your site has %d inactive plugin.',
 445                          'Your site has %d inactive plugins.',
 446                          $unused_plugins
 447                      ),
 448                      $unused_plugins
 449                  ),
 450                  __( 'Inactive plugins are tempting targets for attackers. If you&#8217;re not going to use a plugin, we recommend you remove it.' )
 451              );
 452  
 453              $result['actions'] .= sprintf(
 454                  '<p><a href="%s">%s</a></p>',
 455                  esc_url( admin_url( 'plugins.php?plugin_status=inactive' ) ),
 456                  __( 'Manage inactive plugins' )
 457              );
 458          }
 459  
 460          return $result;
 461      }
 462  
 463      /**
 464       * Test if themes are outdated, or unnecessary.
 465       *
 466       * The tests checks if your site has a default theme (to fall back on if there is a need), if your themes
 467       * are up to date and, finally, encourages you to remove any themes that are not needed.
 468       *
 469       * @since 5.2.0
 470       *
 471       * @return array The test results.
 472       */
 473  	public function get_test_theme_version() {
 474          $result = array(
 475              'label'       => __( 'Your themes are all up to date' ),
 476              'status'      => 'good',
 477              'badge'       => array(
 478                  'label' => __( 'Security' ),
 479                  'color' => 'blue',
 480              ),
 481              'description' => sprintf(
 482                  '<p>%s</p>',
 483                  __( '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.' )
 484              ),
 485              'actions'     => sprintf(
 486                  '<p><a href="%s">%s</a></p>',
 487                  esc_url( admin_url( 'themes.php' ) ),
 488                  __( 'Manage your themes' )
 489              ),
 490              'test'        => 'theme_version',
 491          );
 492  
 493          $theme_updates = get_theme_updates();
 494  
 495          $themes_total        = 0;
 496          $themes_need_updates = 0;
 497          $themes_inactive     = 0;
 498  
 499          // This value is changed during processing to determine how many themes are considered a reasonable amount.
 500          $allowed_theme_count = 1;
 501  
 502          $has_default_theme   = false;
 503          $has_unused_themes   = false;
 504          $show_unused_themes  = true;
 505          $using_default_theme = false;
 506  
 507          // Populate a list of all themes available in the install.
 508          $all_themes   = wp_get_themes();
 509          $active_theme = wp_get_theme();
 510  
 511          // If WP_DEFAULT_THEME doesn't exist, fall back to the latest core default theme.
 512          $default_theme = wp_get_theme( WP_DEFAULT_THEME );
 513          if ( ! $default_theme->exists() ) {
 514              $default_theme = WP_Theme::get_core_default_theme();
 515          }
 516  
 517          if ( $default_theme ) {
 518              $has_default_theme = true;
 519  
 520              if (
 521                  $active_theme->get_stylesheet() === $default_theme->get_stylesheet()
 522              ||
 523                  is_child_theme() && $active_theme->get_template() === $default_theme->get_template()
 524              ) {
 525                  $using_default_theme = true;
 526              }
 527          }
 528  
 529          foreach ( $all_themes as $theme_slug => $theme ) {
 530              $themes_total++;
 531  
 532              if ( array_key_exists( $theme_slug, $theme_updates ) ) {
 533                  $themes_need_updates++;
 534              }
 535          }
 536  
 537          // If this is a child theme, increase the allowed theme count by one, to account for the parent.
 538          if ( is_child_theme() ) {
 539              $allowed_theme_count++;
 540          }
 541  
 542          // If there's a default theme installed and not in use, we count that as allowed as well.
 543          if ( $has_default_theme && ! $using_default_theme ) {
 544              $allowed_theme_count++;
 545          }
 546  
 547          if ( $themes_total > $allowed_theme_count ) {
 548              $has_unused_themes = true;
 549              $themes_inactive   = ( $themes_total - $allowed_theme_count );
 550          }
 551  
 552          // Check if any themes need to be updated.
 553          if ( $themes_need_updates > 0 ) {
 554              $result['status'] = 'critical';
 555  
 556              $result['label'] = __( 'You have themes waiting to be updated' );
 557  
 558              $result['description'] .= sprintf(
 559                  '<p>%s</p>',
 560                  sprintf(
 561                      /* translators: %d: The number of outdated themes. */
 562                      _n(
 563                          'Your site has %d theme waiting to be updated.',
 564                          'Your site has %d themes waiting to be updated.',
 565                          $themes_need_updates
 566                      ),
 567                      $themes_need_updates
 568                  )
 569              );
 570          } else {
 571              // Give positive feedback about the site being good about keeping things up to date.
 572              if ( 1 === $themes_total ) {
 573                  $result['description'] .= sprintf(
 574                      '<p>%s</p>',
 575                      __( 'Your site has 1 installed theme, and it is up to date.' )
 576                  );
 577              } else {
 578                  $result['description'] .= sprintf(
 579                      '<p>%s</p>',
 580                      sprintf(
 581                          /* translators: %d: The number of themes. */
 582                          _n(
 583                              'Your site has %d installed theme, and it is up to date.',
 584                              'Your site has %d installed themes, and they are all up to date.',
 585                              $themes_total
 586                          ),
 587                          $themes_total
 588                      )
 589                  );
 590              }
 591          }
 592  
 593          if ( $has_unused_themes && $show_unused_themes && ! is_multisite() ) {
 594  
 595              // This is a child theme, so we want to be a bit more explicit in our messages.
 596              if ( is_child_theme() ) {
 597                  // Recommend removing inactive themes, except a default theme, your current one, and the parent theme.
 598                  $result['status'] = 'recommended';
 599  
 600                  $result['label'] = __( 'You should remove inactive themes' );
 601  
 602                  if ( $using_default_theme ) {
 603                      $result['description'] .= sprintf(
 604                          '<p>%s %s</p>',
 605                          sprintf(
 606                              /* translators: %d: The number of inactive themes. */
 607                              _n(
 608                                  'Your site has %d inactive theme.',
 609                                  'Your site has %d inactive themes.',
 610                                  $themes_inactive
 611                              ),
 612                              $themes_inactive
 613                          ),
 614                          sprintf(
 615                              /* translators: 1: The currently active theme. 2: The active theme's parent theme. */
 616                              __( 'To enhance your site&#8217;s security, we recommend you remove any themes you&#8217;re not using. You should keep your current theme, %1$s, and %2$s, its parent theme.' ),
 617                              $active_theme->name,
 618                              $active_theme->parent()->name
 619                          )
 620                      );
 621                  } else {
 622                      $result['description'] .= sprintf(
 623                          '<p>%s %s</p>',
 624                          sprintf(
 625                              /* translators: %d: The number of inactive themes. */
 626                              _n(
 627                                  'Your site has %d inactive theme.',
 628                                  'Your site has %d inactive themes.',
 629                                  $themes_inactive
 630                              ),
 631                              $themes_inactive
 632                          ),
 633                          sprintf(
 634                              /* translators: 1: The default theme for WordPress. 2: The currently active theme. 3: The active theme's parent theme. */
 635                              __( 'To enhance your site&#8217;s security, we recommend you remove any themes you&#8217;re not using. You should keep %1$s, the default WordPress theme, %2$s, your current theme, and %3$s, its parent theme.' ),
 636                              $default_theme ? $default_theme->name : WP_DEFAULT_THEME,
 637                              $active_theme->name,
 638                              $active_theme->parent()->name
 639                          )
 640                      );
 641                  }
 642              } else {
 643                  // Recommend removing all inactive themes.
 644                  $result['status'] = 'recommended';
 645  
 646                  $result['label'] = __( 'You should remove inactive themes' );
 647  
 648                  if ( $using_default_theme ) {
 649                      $result['description'] .= sprintf(
 650                          '<p>%s %s</p>',
 651                          sprintf(
 652                              /* translators: 1: The amount of inactive themes. 2: The currently active theme. */
 653                              _n(
 654                                  'Your site has %1$d inactive theme, other than %2$s, your active theme.',
 655                                  'Your site has %1$d inactive themes, other than %2$s, your active theme.',
 656                                  $themes_inactive
 657                              ),
 658                              $themes_inactive,
 659                              $active_theme->name
 660                          ),
 661                          __( 'We recommend removing any unused themes to enhance your site&#8217;s security.' )
 662                      );
 663                  } else {
 664                      $result['description'] .= sprintf(
 665                          '<p>%s %s</p>',
 666                          sprintf(
 667                              /* translators: 1: The amount of inactive themes. 2: The default theme for WordPress. 3: The currently active theme. */
 668                              _n(
 669                                  'Your site has %1$d inactive theme, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
 670                                  'Your site has %1$d inactive themes, other than %2$s, the default WordPress theme, and %3$s, your active theme.',
 671                                  $themes_inactive
 672                              ),
 673                              $themes_inactive,
 674                              $default_theme ? $default_theme->name : WP_DEFAULT_THEME,
 675                              $active_theme->name
 676                          ),
 677                          __( 'We recommend removing any unused themes to enhance your site&#8217;s security.' )
 678                      );
 679                  }
 680              }
 681          }
 682  
 683          // If no default Twenty* theme exists.
 684          if ( ! $has_default_theme ) {
 685              $result['status'] = 'recommended';
 686  
 687              $result['label'] = __( 'Have a default theme available' );
 688  
 689              $result['description'] .= sprintf(
 690                  '<p>%s</p>',
 691                  __( 'Your site does not have any default theme. Default themes are used by WordPress automatically if anything is wrong with your normal theme.' )
 692              );
 693          }
 694  
 695          return $result;
 696      }
 697  
 698      /**
 699       * Test if the supplied PHP version is supported.
 700       *
 701       * @since 5.2.0
 702       *
 703       * @return array The test results.
 704       */
 705  	public function get_test_php_version() {
 706          $response = wp_check_php_version();
 707  
 708          $result = array(
 709              'label'       => sprintf(
 710                  /* translators: %s: The current PHP version. */
 711                  __( 'Your version of PHP (%s) is up to date' ),
 712                  PHP_VERSION
 713              ),
 714              'status'      => 'good',
 715              'badge'       => array(
 716                  'label' => __( 'Performance' ),
 717                  'color' => 'blue',
 718              ),
 719              'description' => sprintf(
 720                  '<p>%s</p>',
 721                  sprintf(
 722                      /* translators: %s: The minimum recommended PHP version. */
 723                      __( 'PHP is the programming language used to build and maintain WordPress. Newer versions of PHP are faster and more secure, so staying up to date will help your site&#8217;s overall performance and security. The minimum recommended version of PHP is %s.' ),
 724                      $response['recommended_version']
 725                  )
 726              ),
 727              'actions'     => sprintf(
 728                  '<p><a href="%s" target="_blank" rel="noopener noreferrer">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
 729                  esc_url( wp_get_update_php_url() ),
 730                  __( 'Learn more about updating PHP' ),
 731                  /* translators: Accessibility text. */
 732                  __( '(opens in a new tab)' )
 733              ),
 734              'test'        => 'php_version',
 735          );
 736  
 737          // PHP is up to date.
 738          if ( ! $response || version_compare( PHP_VERSION, $response['recommended_version'], '>=' ) ) {
 739              return $result;
 740          }
 741  
 742          // The PHP version is older than the recommended version, but still receiving active support.
 743          if ( $response['is_supported'] ) {
 744              $result['label'] = sprintf(
 745                  /* translators: %s: The server PHP version. */
 746                  __( 'Your version of PHP (%s) is out of date' ),
 747                  PHP_VERSION
 748              );
 749              $result['status'] = 'recommended';
 750  
 751              return $result;
 752          }
 753  
 754          // The PHP version is only receiving security fixes.
 755          if ( $response['is_secure'] ) {
 756              $result['label'] = sprintf(
 757                  /* translators: %s: The server PHP version. */
 758                  __( 'Your version of PHP (%s) should be updated' ),
 759                  PHP_VERSION
 760              );
 761              $result['status'] = 'recommended';
 762  
 763              return $result;
 764          }
 765  
 766          // Anything no longer secure must be updated.
 767          $result['label'] = sprintf(
 768              /* translators: %s: The server PHP version. */
 769              __( 'Your version of PHP (%s) requires an update' ),
 770              PHP_VERSION
 771          );
 772          $result['status']         = 'critical';
 773          $result['badge']['label'] = __( 'Security' );
 774  
 775          return $result;
 776      }
 777  
 778      /**
 779       * Check if the passed extension or function are available.
 780       *
 781       * Make the check for available PHP modules into a simple boolean operator for a cleaner test runner.
 782       *
 783       * @since 5.2.0
 784       * @since 5.3.0 The `$constant` and `$class` parameters were added.
 785       *
 786       * @param string $extension Optional. The extension name to test. Default null.
 787       * @param string $function  Optional. The function name to test. Default null.
 788       * @param string $constant  Optional. The constant name to test for. Default null.
 789       * @param string $class     Optional. The class name to test for. Default null.
 790       *
 791       * @return bool Whether or not the extension and function are available.
 792       */
 793  	private function test_php_extension_availability( $extension = null, $function = null, $constant = null, $class = null ) {
 794          // If no extension or function is passed, claim to fail testing, as we have nothing to test against.
 795          if ( ! $extension && ! $function && ! $constant && ! $class ) {
 796              return false;
 797          }
 798  
 799          if ( $extension && ! extension_loaded( $extension ) ) {
 800              return false;
 801          }
 802          if ( $function && ! function_exists( $function ) ) {
 803              return false;
 804          }
 805          if ( $constant && ! defined( $constant ) ) {
 806              return false;
 807          }
 808          if ( $class && ! class_exists( $class ) ) {
 809              return false;
 810          }
 811  
 812          return true;
 813      }
 814  
 815      /**
 816       * Test if required PHP modules are installed on the host.
 817       *
 818       * This test builds on the recommendations made by the WordPress Hosting Team
 819       * as seen at https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions
 820       *
 821       * @since 5.2.0
 822       *
 823       * @return array
 824       */
 825  	public function get_test_php_extensions() {
 826          $result = array(
 827              'label'       => __( 'Required and recommended modules are installed' ),
 828              'status'      => 'good',
 829              'badge'       => array(
 830                  'label' => __( 'Performance' ),
 831                  'color' => 'blue',
 832              ),
 833              'description' => sprintf(
 834                  '<p>%s</p><p>%s</p>',
 835                  __( '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.' ),
 836                  sprintf(
 837                      /* translators: 1: Link to the hosting group page about recommended PHP modules. 2: Additional link attributes. 3: Accessibility text. */
 838                      __( '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>.' ),
 839                      /* translators: Localized team handbook, if one exists. */
 840                      esc_url( __( 'https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions' ) ),
 841                      'target="_blank" rel="noopener noreferrer"',
 842                      sprintf(
 843                          ' <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span>',
 844                          /* translators: Accessibility text. */
 845                          __( '(opens in a new tab)' )
 846                      )
 847                  )
 848              ),
 849              'actions'     => '',
 850              'test'        => 'php_extensions',
 851          );
 852  
 853          $modules = array(
 854              'curl'      => array(
 855                  'function' => 'curl_version',
 856                  'required' => false,
 857              ),
 858              'dom'       => array(
 859                  'class'    => 'DOMNode',
 860                  'required' => false,
 861              ),
 862              'exif'      => array(
 863                  'function' => 'exif_read_data',
 864                  'required' => false,
 865              ),
 866              'fileinfo'  => array(
 867                  'function' => 'finfo_file',
 868                  'required' => false,
 869              ),
 870              'hash'      => array(
 871                  'function' => 'hash',
 872                  'required' => false,
 873              ),
 874              'json'      => array(
 875                  'function' => 'json_last_error',
 876                  'required' => true,
 877              ),
 878              'mbstring'  => array(
 879                  'function' => 'mb_check_encoding',
 880                  'required' => false,
 881              ),
 882              'mysqli'    => array(
 883                  'function' => 'mysqli_connect',
 884                  'required' => false,
 885              ),
 886              'libsodium' => array(
 887                  'constant'            => 'SODIUM_LIBRARY_VERSION',
 888                  'required'            => false,
 889                  'php_bundled_version' => '7.2.0',
 890              ),
 891              'openssl'   => array(
 892                  'function' => 'openssl_encrypt',
 893                  'required' => false,
 894              ),
 895              'pcre'      => array(
 896                  'function' => 'preg_match',
 897                  'required' => false,
 898              ),
 899              'imagick'   => array(
 900                  'extension' => 'imagick',
 901                  'required'  => false,
 902              ),
 903              'mod_xml'   => array(
 904                  'extension' => 'libxml',
 905                  'required'  => false,
 906              ),
 907              'zip'       => array(
 908                  'class'    => 'ZipArchive',
 909                  'required' => false,
 910              ),
 911              'filter'    => array(
 912                  'function' => 'filter_list',
 913                  'required' => false,
 914              ),
 915              'gd'        => array(
 916                  'extension'    => 'gd',
 917                  'required'     => false,
 918                  'fallback_for' => 'imagick',
 919              ),
 920              'iconv'     => array(
 921                  'function' => 'iconv',
 922                  'required' => false,
 923              ),
 924              'mcrypt'    => array(
 925                  'extension'    => 'mcrypt',
 926                  'required'     => false,
 927                  'fallback_for' => 'libsodium',
 928              ),
 929              'simplexml' => array(
 930                  'extension'    => 'simplexml',
 931                  'required'     => false,
 932                  'fallback_for' => 'mod_xml',
 933              ),
 934              'xmlreader' => array(
 935                  'extension'    => 'xmlreader',
 936                  'required'     => false,
 937                  'fallback_for' => 'mod_xml',
 938              ),
 939              'zlib'      => array(
 940                  'extension'    => 'zlib',
 941                  'required'     => false,
 942                  'fallback_for' => 'zip',
 943              ),
 944          );
 945  
 946          /**
 947           * An array representing all the modules we wish to test for.
 948           *
 949           * @since 5.2.0
 950           * @since 5.3.0 The `$constant` and `$class` parameters were added.
 951           *
 952           * @param array $modules {
 953           *     An associated array of modules to test for.
 954           *
 955           *     array $module {
 956           *         An associated array of module properties used during testing.
 957           *         One of either `$function` or `$extension` must be provided, or they will fail by default.
 958           *
 959           *         string $function     Optional. A function name to test for the existence of.
 960           *         string $extension    Optional. An extension to check if is loaded in PHP.
 961           *         string $constant     Optional. A constant name to check for to verify an extension exists.
 962           *         string $class        Optional. A class name to check for to verify an extension exists.
 963           *         bool   $required     Is this a required feature or not.
 964           *         string $fallback_for Optional. The module this module replaces as a fallback.
 965           *     }
 966           * }
 967           */
 968          $modules = apply_filters( 'site_status_test_php_modules', $modules );
 969  
 970          $failures = array();
 971  
 972          foreach ( $modules as $library => $module ) {
 973              $extension  = ( isset( $module['extension'] ) ? $module['extension'] : null );
 974              $function   = ( isset( $module['function'] ) ? $module['function'] : null );
 975              $constant   = ( isset( $module['constant'] ) ? $module['constant'] : null );
 976              $class_name = ( isset( $module['class'] ) ? $module['class'] : null );
 977  
 978              // If this module is a fallback for another function, check if that other function passed.
 979              if ( isset( $module['fallback_for'] ) ) {
 980                  /*
 981                   * If that other function has a failure, mark this module as required for normal operations.
 982                   * If that other function hasn't failed, skip this test as it's only a fallback.
 983                   */
 984                  if ( isset( $failures[ $module['fallback_for'] ] ) ) {
 985                      $module['required'] = true;
 986                  } else {
 987                      continue;
 988                  }
 989              }
 990  
 991              if ( ! $this->test_php_extension_availability( $extension, $function, $constant, $class_name ) && ( ! isset( $module['php_bundled_version'] ) || version_compare( PHP_VERSION, $module['php_bundled_version'], '<' ) ) ) {
 992                  if ( $module['required'] ) {
 993                      $result['status'] = 'critical';
 994  
 995                      $class         = 'error';
 996                      $screen_reader = __( 'Error' );
 997                      $message       = sprintf(
 998                          /* translators: %s: The module name. */
 999                          __( 'The required module, %s, is not installed, or has been disabled.' ),
1000                          $library
1001                      );
1002                  } else {
1003                      $class         = 'warning';
1004                      $screen_reader = __( 'Warning' );
1005                      $message       = sprintf(
1006                          /* translators: %s: The module name. */
1007                          __( 'The optional module, %s, is not installed, or has been disabled.' ),
1008                          $library
1009                      );
1010                  }
1011  
1012                  if ( ! $module['required'] && 'good' === $result['status'] ) {
1013                      $result['status'] = 'recommended';
1014                  }
1015  
1016                  $failures[ $library ] = "<span class='dashicons $class'><span class='screen-reader-text'>$screen_reader</span></span> $message";
1017              }
1018          }
1019  
1020          if ( ! empty( $failures ) ) {
1021              $output = '<ul>';
1022  
1023              foreach ( $failures as $failure ) {
1024                  $output .= sprintf(
1025                      '<li>%s</li>',
1026                      $failure
1027                  );
1028              }
1029  
1030              $output .= '</ul>';
1031          }
1032  
1033          if ( 'good' !== $result['status'] ) {
1034              if ( 'recommended' === $result['status'] ) {
1035                  $result['label'] = __( 'One or more recommended modules are missing' );
1036              }
1037              if ( 'critical' === $result['status'] ) {
1038                  $result['label'] = __( 'One or more required modules are missing' );
1039              }
1040  
1041              $result['description'] .= sprintf(
1042                  '<p>%s</p>',
1043                  $output
1044              );
1045          }
1046  
1047          return $result;
1048      }
1049  
1050      /**
1051       * Test if the PHP default timezone is set to UTC.
1052       *
1053       * @since 5.3.1
1054       *
1055       * @return array The test results.
1056       */
1057  	public function get_test_php_default_timezone() {
1058          $result = array(
1059              'label'       => __( 'PHP default timezone is valid' ),
1060              'status'      => 'good',
1061              'badge'       => array(
1062                  'label' => __( 'Performance' ),
1063                  'color' => 'blue',
1064              ),
1065              'description' => sprintf(
1066                  '<p>%s</p>',
1067                  __( 'PHP default timezone was configured by WordPress on loading. This is necessary for correct calculations of dates and times.' )
1068              ),
1069              'test'        => 'php_default_timezone',
1070          );
1071  
1072          if ( 'UTC' !== date_default_timezone_get() ) {
1073              $result['status'] = 'critical';
1074  
1075              $result['label'] = __( 'PHP default timezone is invalid' );
1076  
1077              $result['description'] = sprintf(
1078                  '<p>%s</p>',
1079                  sprintf(
1080                      /* translators: %s: date_default_timezone_set() */
1081                      __( 'PHP default timezone was changed after WordPress loading by a %s function call. This interferes with correct calculations of dates and times.' ),
1082                      '<code>date_default_timezone_set()</code>'
1083                  )
1084              );
1085          }
1086  
1087          return $result;
1088      }
1089  
1090      /**
1091       * Test if the SQL server is up to date.
1092       *
1093       * @since 5.2.0
1094       *
1095       * @return array The test results.
1096       */
1097  	public function get_test_sql_server() {
1098          $result = array(
1099              'label'       => __( 'SQL server is up to date' ),
1100              'status'      => 'good',
1101              'badge'       => array(
1102                  'label' => __( 'Performance' ),
1103                  'color' => 'blue',
1104              ),
1105              'description' => sprintf(
1106                  '<p>%s</p>',
1107                  __( 'The SQL server is a required piece of software for the database WordPress uses to store all your site&#8217;s content and settings.' )
1108              ),
1109              'actions'     => sprintf(
1110                  '<p><a href="%s" target="_blank" rel="noopener noreferrer">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1111                  /* translators: Localized version of WordPress requirements if one exists. */
1112                  esc_url( __( 'https://wordpress.org/about/requirements/' ) ),
1113                  __( 'Learn more about what WordPress requires to run.' ),
1114                  /* translators: Accessibility text. */
1115                  __( '(opens in a new tab)' )
1116              ),
1117              'test'        => 'sql_server',
1118          );
1119  
1120          $db_dropin = file_exists( WP_CONTENT_DIR . '/db.php' );
1121  
1122          if ( ! $this->mysql_rec_version_check ) {
1123              $result['status'] = 'recommended';
1124  
1125              $result['label'] = __( 'Outdated SQL server' );
1126  
1127              $result['description'] .= sprintf(
1128                  '<p>%s</p>',
1129                  sprintf(
1130                      /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server recommended version number. */
1131                      __( 'For optimal performance and security reasons, we recommend running %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
1132                      ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
1133                      $this->health_check_mysql_rec_version
1134                  )
1135              );
1136          }
1137  
1138          if ( ! $this->mysql_min_version_check ) {
1139              $result['status'] = 'critical';
1140  
1141              $result['label']          = __( 'Severely outdated SQL server' );
1142              $result['badge']['label'] = __( 'Security' );
1143  
1144              $result['description'] .= sprintf(
1145                  '<p>%s</p>',
1146                  sprintf(
1147                      /* translators: 1: The database engine in use (MySQL or MariaDB). 2: Database server minimum version number. */
1148                      __( 'WordPress requires %1$s version %2$s or higher. Contact your web hosting company to correct this.' ),
1149                      ( $this->is_mariadb ? 'MariaDB' : 'MySQL' ),
1150                      $this->health_check_mysql_required_version
1151                  )
1152              );
1153          }
1154  
1155          if ( $db_dropin ) {
1156              $result['description'] .= sprintf(
1157                  '<p>%s</p>',
1158                  wp_kses(
1159                      sprintf(
1160                          /* translators: 1: The name of the drop-in. 2: The name of the database engine. */
1161                          __( 'You are using a %1$s drop-in which might mean that a %2$s database is not being used.' ),
1162                          '<code>wp-content/db.php</code>',
1163                          ( $this->is_mariadb ? 'MariaDB' : 'MySQL' )
1164                      ),
1165                      array(
1166                          'code' => true,
1167                      )
1168                  )
1169              );
1170          }
1171  
1172          return $result;
1173      }
1174  
1175      /**
1176       * Test if the database server is capable of using utf8mb4.
1177       *
1178       * @since 5.2.0
1179       *
1180       * @return array The test results.
1181       */
1182  	public function get_test_utf8mb4_support() {
1183          global $wpdb;
1184  
1185          $result = array(
1186              'label'       => __( 'UTF8MB4 is supported' ),
1187              'status'      => 'good',
1188              'badge'       => array(
1189                  'label' => __( 'Performance' ),
1190                  'color' => 'blue',
1191              ),
1192              'description' => sprintf(
1193                  '<p>%s</p>',
1194                  __( '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.' )
1195              ),
1196              'actions'     => '',
1197              'test'        => 'utf8mb4_support',
1198          );
1199  
1200          if ( ! $this->is_mariadb ) {
1201              if ( version_compare( $this->mysql_server_version, '5.5.3', '<' ) ) {
1202                  $result['status'] = 'recommended';
1203  
1204                  $result['label'] = __( 'utf8mb4 requires a MySQL update' );
1205  
1206                  $result['description'] .= sprintf(
1207                      '<p>%s</p>',
1208                      sprintf(
1209                          /* translators: %s: Version number. */
1210                          __( 'WordPress&#8217; utf8mb4 support requires MySQL version %s or greater. Please contact your server administrator.' ),
1211                          '5.5.3'
1212                      )
1213                  );
1214              } else {
1215                  $result['description'] .= sprintf(
1216                      '<p>%s</p>',
1217                      __( 'Your MySQL version supports utf8mb4.' )
1218                  );
1219              }
1220          } else { // MariaDB introduced utf8mb4 support in 5.5.0
1221              if ( version_compare( $this->mysql_server_version, '5.5.0', '<' ) ) {
1222                  $result['status'] = 'recommended';
1223  
1224                  $result['label'] = __( 'utf8mb4 requires a MariaDB update' );
1225  
1226                  $result['description'] .= sprintf(
1227                      '<p>%s</p>',
1228                      sprintf(
1229                          /* translators: %s: Version number. */
1230                          __( 'WordPress&#8217; utf8mb4 support requires MariaDB version %s or greater. Please contact your server administrator.' ),
1231                          '5.5.0'
1232                      )
1233                  );
1234              } else {
1235                  $result['description'] .= sprintf(
1236                      '<p>%s</p>',
1237                      __( 'Your MariaDB version supports utf8mb4.' )
1238                  );
1239              }
1240          }
1241  
1242          if ( $wpdb->use_mysqli ) {
1243              // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysqli_get_client_info
1244              $mysql_client_version = mysqli_get_client_info();
1245          } else {
1246              // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysql_get_client_info,PHPCompatibility.Extensions.RemovedExtensions.mysql_DeprecatedRemoved
1247              $mysql_client_version = mysql_get_client_info();
1248          }
1249  
1250          /*
1251           * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
1252           * mysqlnd has supported utf8mb4 since 5.0.9.
1253           */
1254          if ( false !== strpos( $mysql_client_version, 'mysqlnd' ) ) {
1255              $mysql_client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $mysql_client_version );
1256              if ( version_compare( $mysql_client_version, '5.0.9', '<' ) ) {
1257                  $result['status'] = 'recommended';
1258  
1259                  $result['label'] = __( 'utf8mb4 requires a newer client library' );
1260  
1261                  $result['description'] .= sprintf(
1262                      '<p>%s</p>',
1263                      sprintf(
1264                          /* translators: 1: Name of the library, 2: Number of version. */
1265                          __( 'WordPress&#8217; utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ),
1266                          'mysqlnd',
1267                          '5.0.9'
1268                      )
1269                  );
1270              }
1271          } else {
1272              if ( version_compare( $mysql_client_version, '5.5.3', '<' ) ) {
1273                  $result['status'] = 'recommended';
1274  
1275                  $result['label'] = __( 'utf8mb4 requires a newer client library' );
1276  
1277                  $result['description'] .= sprintf(
1278                      '<p>%s</p>',
1279                      sprintf(
1280                          /* translators: 1: Name of the library, 2: Number of version. */
1281                          __( 'WordPress&#8217; utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ),
1282                          'libmysql',
1283                          '5.5.3'
1284                      )
1285                  );
1286              }
1287          }
1288  
1289          return $result;
1290      }
1291  
1292      /**
1293       * Test if the site can communicate with WordPress.org.
1294       *
1295       * @since 5.2.0
1296       *
1297       * @return array The test results.
1298       */
1299  	public function get_test_dotorg_communication() {
1300          $result = array(
1301              'label'       => __( 'Can communicate with WordPress.org' ),
1302              'status'      => '',
1303              'badge'       => array(
1304                  'label' => __( 'Security' ),
1305                  'color' => 'blue',
1306              ),
1307              'description' => sprintf(
1308                  '<p>%s</p>',
1309                  __( 'Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.' )
1310              ),
1311              'actions'     => '',
1312              'test'        => 'dotorg_communication',
1313          );
1314  
1315          $wp_dotorg = wp_remote_get(
1316              'https://api.wordpress.org',
1317              array(
1318                  'timeout' => 10,
1319              )
1320          );
1321          if ( ! is_wp_error( $wp_dotorg ) ) {
1322              $result['status'] = 'good';
1323          } else {
1324              $result['status'] = 'critical';
1325  
1326              $result['label'] = __( 'Could not reach WordPress.org' );
1327  
1328              $result['description'] .= sprintf(
1329                  '<p>%s</p>',
1330                  sprintf(
1331                      '<span class="error"><span class="screen-reader-text">%s</span></span> %s',
1332                      __( 'Error' ),
1333                      sprintf(
1334                          /* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */
1335                          __( 'Your site is unable to reach WordPress.org at %1$s, and returned the error: %2$s' ),
1336                          gethostbyname( 'api.wordpress.org' ),
1337                          $wp_dotorg->get_error_message()
1338                      )
1339                  )
1340              );
1341  
1342              $result['actions'] = sprintf(
1343                  '<p><a href="%s" target="_blank" rel="noopener noreferrer">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1344                  /* translators: Localized Support reference. */
1345                  esc_url( __( 'https://wordpress.org/support' ) ),
1346                  __( 'Get help resolving this issue.' ),
1347                  /* translators: Accessibility text. */
1348                  __( '(opens in a new tab)' )
1349              );
1350          }
1351  
1352          return $result;
1353      }
1354  
1355      /**
1356       * Test if debug information is enabled.
1357       *
1358       * When WP_DEBUG is enabled, errors and information may be disclosed to site visitors, or it may be
1359       * logged to a publicly accessible file.
1360       *
1361       * Debugging is also frequently left enabled after looking for errors on a site, as site owners do
1362       * not understand the implications of this.
1363       *
1364       * @since 5.2.0
1365       *
1366       * @return array The test results.
1367       */
1368  	public function get_test_is_in_debug_mode() {
1369          $result = array(
1370              'label'       => __( 'Your site is not set to output debug information' ),
1371              'status'      => 'good',
1372              'badge'       => array(
1373                  'label' => __( 'Security' ),
1374                  'color' => 'blue',
1375              ),
1376              'description' => sprintf(
1377                  '<p>%s</p>',
1378                  __( '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.' )
1379              ),
1380              'actions'     => sprintf(
1381                  '<p><a href="%s" target="_blank" rel="noopener noreferrer">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1382                  /* translators: Documentation explaining debugging in WordPress. */
1383                  esc_url( __( 'https://wordpress.org/support/article/debugging-in-wordpress/' ) ),
1384                  __( 'Learn more about debugging in WordPress.' ),
1385                  /* translators: Accessibility text. */
1386                  __( '(opens in a new tab)' )
1387              ),
1388              'test'        => 'is_in_debug_mode',
1389          );
1390  
1391          if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
1392              if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
1393                  $result['label'] = __( 'Your site is set to log errors to a potentially public file.' );
1394  
1395                  $result['status'] = 'critical';
1396  
1397                  $result['description'] .= sprintf(
1398                      '<p>%s</p>',
1399                      sprintf(
1400                          /* translators: %s: WP_DEBUG_LOG */
1401                          __( '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 normal users.' ),
1402                          '<code>WP_DEBUG_LOG</code>'
1403                      )
1404                  );
1405              }
1406  
1407              if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) {
1408                  $result['label'] = __( 'Your site is set to display errors to site visitors' );
1409  
1410                  $result['status'] = 'critical';
1411  
1412                  $result['description'] .= sprintf(
1413                      '<p>%s</p>',
1414                      sprintf(
1415                          /* translators: 1: WP_DEBUG_DISPLAY, 2: WP_DEBUG */
1416                          __( '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.' ),
1417                          '<code>WP_DEBUG_DISPLAY</code>',
1418                          '<code>WP_DEBUG</code>'
1419                      )
1420                  );
1421              }
1422          }
1423  
1424          return $result;
1425      }
1426  
1427      /**
1428       * Test if your site is serving content over HTTPS.
1429       *
1430       * Many sites have varying degrees of HTTPS support, the most common of which is sites that have it
1431       * enabled, but only if you visit the right site address.
1432       *
1433       * @since 5.2.0
1434       *
1435       * @return array The test results.
1436       */
1437  	public function get_test_https_status() {
1438          $result = array(
1439              'label'       => __( 'Your website is using an active HTTPS connection.' ),
1440              'status'      => 'good',
1441              'badge'       => array(
1442                  'label' => __( 'Security' ),
1443                  'color' => 'blue',
1444              ),
1445              'description' => sprintf(
1446                  '<p>%s</p>',
1447                  __( '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.' )
1448              ),
1449              'actions'     => sprintf(
1450                  '<p><a href="%s" target="_blank" rel="noopener noreferrer">%s <span class="screen-reader-text">%s</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a></p>',
1451                  /* translators: Documentation explaining HTTPS and why it should be used. */
1452                  esc_url( __( 'https://wordpress.org/support/article/why-should-i-use-https/' ) ),
1453                  __( 'Learn more about why you should use HTTPS' ),
1454                  /* translators: Accessibility text. */
1455                  __( '(opens in a new tab)' )
1456              ),
1457              'test'        => 'https_status',
1458          );
1459  
1460          if ( is_ssl() ) {
1461              $wp_url   = get_bloginfo( 'wpurl' );
1462              $site_url = get_bloginfo( 'url' );
1463  
1464              if ( 'https' !== substr( $wp_url, 0, 5 ) || 'https' !== substr( $site_url, 0, 5 ) ) {
1465                  $result['status'] = 'recommended';
1466  
1467                  $result['label'] = __( 'Only parts of your site are using HTTPS' );
1468  
1469                  $result['description'] = sprintf(
1470                      '<p>%s</p>',
1471                      sprintf(
1472                          /* translators: %s: URL to General Settings screen. */
1473                          __( 'You are accessing this website using HTTPS, but your <a href="%s">WordPress Address</a> is not set up to use HTTPS by default.' ),
1474                          esc_url( admin_url( 'options-general.php' ) )
1475                      )
1476                  );
1477  
1478                  $result['actions'] .= sprintf(
1479                      '<p><a href="%s">%s</a></p>',
1480                      esc_url( admin_url( 'options-general.php' ) ),
1481                      __( 'Update your site addresses' )
1482                  );
1483              }
1484          } else {
1485              $result['status'] = 'recommended';
1486  
1487              $result['label'] = __( 'Your site does not use HTTPS' );
1488          }
1489  
1490          return $result;
1491      }
1492  
1493      /**
1494       * Check if the HTTP API can handle SSL/TLS requests.
1495       *
1496       * @since 5.2.0
1497       *
1498       * @return array The test results.
1499       */
1500  	public function get_test_ssl_support() {
1501          $result = array(
1502              'label'       => '',
1503              'status'      => '',
1504              'badge'       => array(
1505                  'label' => __( 'Security' ),
1506                  'color' => 'blue',
1507              ),
1508              'description' => sprintf(
1509                  '<p>%s</p>',
1510                  __( 'Securely communicating between servers are needed for transactions such as fetching files, conducting sales on store sites, and much more.' )
1511              ),
1512              'actions'     => '',
1513              'test'        => 'ssl_support',
1514          );
1515  
1516          $supports_https = wp_http_supports( array( 'ssl' ) );
1517  
1518          if ( $supports_https ) {
1519              $result['status'] = 'good';
1520  
1521              $result['label'] = __( 'Your site can communicate securely with other services' );
1522          } else {
1523              $result['status'] = 'critical';
1524  
1525              $result['label'] = __( 'Your site is unable to communicate securely with other services' );
1526  
1527              $result['description'] .= sprintf(
1528                  '<p>%s</p>',
1529                  __( 'Talk to your web host about OpenSSL support for PHP.' )
1530              );
1531          }
1532  
1533          return $result;
1534      }
1535  
1536      /**
1537       * Test if scheduled events run as intended.
1538       *
1539       * If scheduled events are not running, this may indicate something with WP_Cron is not working as intended,
1540       * or that there are orphaned events hanging around from older code.
1541       *
1542       * @since 5.2.0
1543       *
1544       * @return array The test results.
1545       */
1546  	public function get_test_scheduled_events() {
1547          $result = array(
1548              'label'       => __( 'Scheduled events are running' ),
1549              'status'      => 'good',
1550              'badge'       => array(
1551                  'label' => __( 'Performance' ),
1552                  'color' => 'blue',
1553              ),
1554              'description' => sprintf(
1555                  '<p>%s</p>',
1556                  __( '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.' )
1557              ),
1558              'actions'     => '',
1559              'test'        => 'scheduled_events',
1560          );
1561  
1562          $this->wp_schedule_test_init();
1563  
1564          if ( is_wp_error( $this->has_missed_cron() ) ) {
1565              $result['status'] = 'critical';
1566  
1567              $result['label'] = __( 'It was not possible to check your scheduled events' );
1568  
1569              $result['description'] = sprintf(
1570                  '<p>%s</p>',
1571                  sprintf(
1572                      /* translators: %s: The error message returned while from the cron scheduler. */
1573                      __( 'While trying to test your site&#8217;s scheduled events, the following error was returned: %s' ),
1574                      $this->has_missed_cron()->get_error_message()
1575                  )
1576              );
1577          } elseif ( $this->has_missed_cron() ) {
1578              $result['status'] = 'recommended';
1579  
1580              $result['label'] = __( 'A scheduled event has failed' );
1581  
1582              $result['description'] = sprintf(
1583                  '<p>%s</p>',
1584                  sprintf(
1585                      /* translators: %s: The name of the failed cron event. */
1586                      __( '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.' ),
1587                      $this->last_missed_cron
1588                  )
1589              );
1590          } elseif ( $this->has_late_cron() ) {
1591              $result['status'] = 'recommended';
1592  
1593              $result['label'] = __( 'A scheduled event is late' );
1594  
1595              $result['description'] = sprintf(
1596                  '<p>%s</p>',
1597                  sprintf(
1598                      /* translators: %s: The name of the late cron event. */
1599                      __( '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.' ),
1600                      $this->last_late_cron
1601                  )
1602              );
1603          }
1604  
1605          return $result;
1606      }
1607  
1608      /**
1609       * Test if WordPress can run automated background updates.
1610       *
1611       * Background updates in WordPress are primarily used for minor releases and security updates. It's important
1612       * to either have these working, or be aware that they are intentionally disabled for whatever reason.
1613       *
1614       * @since 5.2.0
1615       *
1616       * @return array The test results.
1617       */
1618  	public function get_test_background_updates() {
1619          $result = array(
1620              'label'       => __( 'Background updates are working' ),
1621              'status'      => 'good',
1622              'badge'       => array(
1623                  'label' => __( 'Security' ),
1624                  'color' => 'blue',
1625              ),
1626              'description' => sprintf(
1627                  '<p>%s</p>',
1628                  __( 'Background updates ensure that WordPress can auto-update if a security update is released for the version you are currently using.' )
1629              ),
1630              'actions'     => '',
1631              'test'        => 'background_updates',
1632          );
1633  
1634          if ( ! class_exists( 'WP_Site_Health_Auto_Updates' ) ) {
1635              require_once( ABSPATH . 'wp-admin/includes/class-wp-site-health-auto-updates.php' );
1636          }
1637  
1638          // Run the auto-update tests in a separate class,
1639          // as there are many considerations to be made.
1640          $automatic_updates = new WP_Site_Health_Auto_Updates();
1641          $tests             = $automatic_updates->run_tests();
1642  
1643          $output = '<ul>';
1644  
1645          foreach ( $tests as $test ) {
1646              $severity_string = __( 'Passed' );
1647  
1648              if ( 'fail' === $test->severity ) {
1649                  $result['label'] = __( 'Background updates are not working as expected' );
1650  
1651                  $result['status'] = 'critical';
1652  
1653                  $severity_string = __( 'Error' );
1654              }
1655  
1656              if ( 'warning' === $test->severity && 'good' === $result['status'] ) {
1657                  $result['label'] = __( 'Background updates may not be working properly' );
1658  
1659                  $result['status'] = 'recommended';
1660  
1661                  $severity_string = __( 'Warning' );
1662              }
1663  
1664              $output .= sprintf(
1665                  '<li><span class="dashicons %s"><span class="screen-reader-text">%s</span></span> %s</li>',
1666                  esc_attr( $test->severity ),
1667                  $severity_string,
1668                  $test->description
1669              );
1670          }
1671  
1672          $output .= '</ul>';
1673  
1674          if ( 'good' !== $result['status'] ) {
1675              $result['description'] .= sprintf(
1676                  '<p>%s</p>',
1677                  $output
1678              );
1679          }
1680  
1681          return $result;
1682      }
1683  
1684      /**
1685       * Test if loopbacks work as expected.
1686       *
1687       * A loopback is when WordPress queries itself, for example to start a new WP_Cron instance, or when editing a
1688       * plugin or theme. This has shown itself to be a recurring issue as code can very easily break this interaction.
1689       *
1690       * @since 5.2.0
1691       *
1692       * @return array The test results.
1693       */
1694  	public function get_test_loopback_requests() {
1695          $result = array(
1696              'label'       => __( 'Your site can perform loopback requests' ),
1697              'status'      => 'good',
1698              'badge'       => array(
1699                  'label' => __( 'Performance' ),
1700                  'color' => 'blue',
1701              ),
1702              'description' => sprintf(
1703                  '<p>%s</p>',
1704                  __( '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.' )
1705              ),
1706              'actions'     => '',
1707              'test'        => 'loopback_requests',
1708          );
1709  
1710          $check_loopback = $this->can_perform_loopback();
1711  
1712          $result['status'] = $check_loopback->status;
1713  
1714          if ( 'good' !== $check_loopback->status ) {
1715              $result['label'] = __( 'Your site could not complete a loopback request' );
1716  
1717              $result['description'] .= sprintf(
1718                  '<p>%s</p>',
1719                  $check_loopback->message
1720              );
1721          }
1722  
1723          return $result;
1724      }
1725  
1726      /**
1727       * Test if HTTP requests are blocked.
1728       *
1729       * It's possible to block all outgoing communication (with the possibility of whitelisting hosts) via the
1730       * HTTP API. This may create problems for users as many features are running as services these days.
1731       *
1732       * @since 5.2.0
1733       *
1734       * @return array The test results.
1735       */
1736  	public function get_test_http_requests() {
1737          $result = array(
1738              'label'       => __( 'HTTP requests seem to be working as expected' ),
1739              'status'      => 'good',
1740              'badge'       => array(
1741                  'label' => __( 'Performance' ),
1742                  'color' => 'blue',
1743              ),
1744              'description' => sprintf(
1745                  '<p>%s</p>',
1746                  __( '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.' )
1747              ),
1748              'actions'     => '',
1749              'test'        => 'http_requests',
1750          );
1751  
1752          $blocked = false;
1753          $hosts   = array();
1754  
1755          if ( defined( 'WP_HTTP_BLOCK_EXTERNAL' ) && WP_HTTP_BLOCK_EXTERNAL ) {
1756              $blocked = true;
1757          }
1758  
1759          if ( defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
1760              $hosts = explode( ',', WP_ACCESSIBLE_HOSTS );
1761          }
1762  
1763          if ( $blocked && 0 === sizeof( $hosts ) ) {
1764              $result['status'] = 'critical';
1765  
1766              $result['label'] = __( 'HTTP requests are blocked' );
1767  
1768              $result['description'] .= sprintf(
1769                  '<p>%s</p>',
1770                  sprintf(
1771                      /* translators: %s: Name of the constant used. */
1772                      __( 'HTTP requests have been blocked by the %s constant, with no allowed hosts.' ),
1773                      '<code>WP_HTTP_BLOCK_EXTERNAL</code>'
1774                  )
1775              );
1776          }
1777  
1778          if ( $blocked && 0 < sizeof( $hosts ) ) {
1779              $result['status'] = 'recommended';
1780  
1781              $result['label'] = __( 'HTTP requests are partially blocked' );
1782  
1783              $result['description'] .= sprintf(
1784                  '<p>%s</p>',
1785                  sprintf(
1786                      /* translators: 1: Name of the constant used. 2: List of hostnames whitelisted. */
1787                      __( 'HTTP requests have been blocked by the %1$s constant, with some hosts whitelisted: %2$s.' ),
1788                      '<code>WP_HTTP_BLOCK_EXTERNAL</code>',
1789                      implode( ',', $hosts )
1790                  )
1791              );
1792          }
1793  
1794          return $result;
1795      }
1796  
1797      /**
1798       * Test if the REST API is accessible.
1799       *
1800       * Various security measures may block the REST API from working, or it may have been disabled in general.
1801       * This is required for the new block editor to work, so we explicitly test for this.
1802       *
1803       * @since 5.2.0
1804       *
1805       * @return array The test results.
1806       */
1807  	public function get_test_rest_availability() {
1808          $result = array(
1809              'label'       => __( 'The REST API is available' ),
1810              'status'      => 'good',
1811              'badge'       => array(
1812                  'label' => __( 'Performance' ),
1813                  'color' => 'blue',
1814              ),
1815              'description' => sprintf(
1816                  '<p>%s</p>',
1817                  __( 'The REST API is one way WordPress, and other applications, communicate with the server. One example is the block editor screen, which relies on this to display, and save, your posts and pages.' )
1818              ),
1819              'actions'     => '',
1820              'test'        => 'rest_availability',
1821          );
1822  
1823          $cookies = wp_unslash( $_COOKIE );
1824          $timeout = 10;
1825          $headers = array(
1826              'Cache-Control' => 'no-cache',
1827              'X-WP-Nonce'    => wp_create_nonce( 'wp_rest' ),
1828          );
1829          /** This filter is documented in wp-includes/class-wp-http-streams.php */
1830          $sslverify = apply_filters( 'https_local_ssl_verify', false );
1831  
1832          // Include Basic auth in loopback requests.
1833          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
1834              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
1835          }
1836  
1837          $url = rest_url( 'wp/v2/types/post' );
1838  
1839          // The context for this is editing with the new block editor.
1840          $url = add_query_arg(
1841              array(
1842                  'context' => 'edit',
1843              ),
1844              $url
1845          );
1846  
1847          $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
1848  
1849          if ( is_wp_error( $r ) ) {
1850              $result['status'] = 'critical';
1851  
1852              $result['label'] = __( 'The REST API encountered an error' );
1853  
1854              $result['description'] .= sprintf(
1855                  '<p>%s</p>',
1856                  sprintf(
1857                      '%s<br>%s',
1858                      __( 'The REST API request failed due to an error.' ),
1859                      sprintf(
1860                          /* translators: 1: The HTTP response code. 2: The error message returned. */
1861                          __( 'Error: [%1$s] %2$s' ),
1862                          wp_remote_retrieve_response_code( $r ),
1863                          $r->get_error_message()
1864                      )
1865                  )
1866              );
1867          } elseif ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
1868              $result['status'] = 'recommended';
1869  
1870              $result['label'] = __( 'The REST API encountered an unexpected result' );
1871  
1872              $result['description'] .= sprintf(
1873                  '<p>%s</p>',
1874                  sprintf(
1875                      /* translators: 1: The HTTP response code returned. 2: The error message returned. */
1876                      __( 'The REST API call gave the following unexpected result: (%1$d) %2$s.' ),
1877                      wp_remote_retrieve_response_code( $r ),
1878                      wp_remote_retrieve_body( $r )
1879                  )
1880              );
1881          } else {
1882              $json = json_decode( wp_remote_retrieve_body( $r ), true );
1883  
1884              if ( false !== $json && ! isset( $json['capabilities'] ) ) {
1885                  $result['status'] = 'recommended';
1886  
1887                  $result['label'] = __( 'The REST API did not behave correctly' );
1888  
1889                  $result['description'] .= sprintf(
1890                      '<p>%s</p>',
1891                      sprintf(
1892                          /* translators: %s: The name of the query parameter being tested. */
1893                          __( 'The REST API did not process the %s query parameter correctly.' ),
1894                          '<code>context</code>'
1895                      )
1896                  );
1897              }
1898          }
1899  
1900          return $result;
1901      }
1902  
1903      /**
1904       * Return a set of tests that belong to the site status page.
1905       *
1906       * Each site status test is defined here, they may be `direct` tests, that run on page load, or `async` tests
1907       * which will run later down the line via JavaScript calls to improve page performance and hopefully also user
1908       * experiences.
1909       *
1910       * @since 5.2.0
1911       *
1912       * @return array The list of tests to run.
1913       */
1914  	public static function get_tests() {
1915          $tests = array(
1916              'direct' => array(
1917                  'wordpress_version'    => array(
1918                      'label' => __( 'WordPress Version' ),
1919                      'test'  => 'wordpress_version',
1920                  ),
1921                  'plugin_version'       => array(
1922                      'label' => __( 'Plugin Versions' ),
1923                      'test'  => 'plugin_version',
1924                  ),
1925                  'theme_version'        => array(
1926                      'label' => __( 'Theme Versions' ),
1927                      'test'  => 'theme_version',
1928                  ),
1929                  'php_version'          => array(
1930                      'label' => __( 'PHP Version' ),
1931                      'test'  => 'php_version',
1932                  ),
1933                  'php_extensions'       => array(
1934                      'label' => __( 'PHP Extensions' ),
1935                      'test'  => 'php_extensions',
1936                  ),
1937                  'php_default_timezone' => array(
1938                      'label' => __( 'PHP Default Timezone' ),
1939                      'test'  => 'php_default_timezone',
1940                  ),
1941                  'sql_server'           => array(
1942                      'label' => __( 'Database Server version' ),
1943                      'test'  => 'sql_server',
1944                  ),
1945                  'utf8mb4_support'      => array(
1946                      'label' => __( 'MySQL utf8mb4 support' ),
1947                      'test'  => 'utf8mb4_support',
1948                  ),
1949                  'https_status'         => array(
1950                      'label' => __( 'HTTPS status' ),
1951                      'test'  => 'https_status',
1952                  ),
1953                  'ssl_support'          => array(
1954                      'label' => __( 'Secure communication' ),
1955                      'test'  => 'ssl_support',
1956                  ),
1957                  'scheduled_events'     => array(
1958                      'label' => __( 'Scheduled events' ),
1959                      'test'  => 'scheduled_events',
1960                  ),
1961                  'http_requests'        => array(
1962                      'label' => __( 'HTTP Requests' ),
1963                      'test'  => 'http_requests',
1964                  ),
1965                  'debug_enabled'        => array(
1966                      'label' => __( 'Debugging enabled' ),
1967                      'test'  => 'is_in_debug_mode',
1968                  ),
1969              ),
1970              'async'  => array(
1971                  'dotorg_communication' => array(
1972                      'label' => __( 'Communication with WordPress.org' ),
1973                      'test'  => 'dotorg_communication',
1974                  ),
1975                  'background_updates'   => array(
1976                      'label' => __( 'Background updates' ),
1977                      'test'  => 'background_updates',
1978                  ),
1979                  'loopback_requests'    => array(
1980                      'label' => __( 'Loopback request' ),
1981                      'test'  => 'loopback_requests',
1982                  ),
1983              ),
1984          );
1985  
1986          // Conditionally include REST rules if the function for it exists.
1987          if ( function_exists( 'rest_url' ) ) {
1988              $tests['direct']['rest_availability'] = array(
1989                  'label' => __( 'REST API availability' ),
1990                  'test'  => 'rest_availability',
1991              );
1992          }
1993  
1994          /**
1995           * Add or modify which site status tests are run on a site.
1996           *
1997           * The site health is determined by a set of tests based on best practices from
1998           * both the WordPress Hosting Team, but also web standards in general.
1999           *
2000           * Some sites may not have the same requirements, for example the automatic update
2001           * checks may be handled by a host, and are therefore disabled in core.
2002           * Or maybe you want to introduce a new test, is caching enabled/disabled/stale for example.
2003           *
2004           * Tests may be added either as direct, or asynchronous ones. Any test that may require some time
2005           * to complete should run asynchronously, to avoid extended loading periods within wp-admin.
2006           *
2007           * @since 5.2.0
2008           *
2009           * @param array $test_type {
2010           *     An associative array, where the `$test_type` is either `direct` or
2011           *     `async`, to declare if the test should run via AJAX calls after page load.
2012           *
2013           *     @type array $identifier {
2014           *         `$identifier` should be a unique identifier for the test that should run.
2015           *         Plugins and themes are encouraged to prefix test identifiers with their slug
2016           *         to avoid any collisions between tests.
2017           *
2018           *         @type string $label A friendly label for your test to identify it by.
2019           *         @type mixed  $test  A callable to perform a direct test, or a string AJAX action to be called
2020           *                             to perform an async test.
2021           *     }
2022           * }
2023           */
2024          $tests = apply_filters( 'site_status_tests', $tests );
2025  
2026          return $tests;
2027      }
2028  
2029      /**
2030       * Add a class to the body HTML tag.
2031       *
2032       * Filters the body class string for admin pages and adds our own class for easier styling.
2033       *
2034       * @since 5.2.0
2035       *
2036       * @param string $body_class The body class string.
2037       * @return string The modified body class string.
2038       */
2039  	public function admin_body_class( $body_class ) {
2040          $screen = get_current_screen();
2041          if ( 'site-health' !== $screen->id ) {
2042              return $body_class;
2043          }
2044  
2045          $body_class .= ' site-health';
2046  
2047          return $body_class;
2048      }
2049  
2050      /**
2051       * Initiate the WP_Cron schedule test cases.
2052       *
2053       * @since 5.2.0
2054       */
2055  	private function wp_schedule_test_init() {
2056          $this->schedules = wp_get_schedules();
2057          $this->get_cron_tasks();
2058      }
2059  
2060      /**
2061       * Populate our list of cron events and store them to a class-wide variable.
2062       *
2063       * @since 5.2.0
2064       */
2065  	private function get_cron_tasks() {
2066          $cron_tasks = _get_cron_array();
2067  
2068          if ( empty( $cron_tasks ) ) {
2069              $this->crons = new WP_Error( 'no_tasks', __( 'No scheduled events exist on this site.' ) );
2070              return;
2071          }
2072  
2073          $this->crons = array();
2074  
2075          foreach ( $cron_tasks as $time => $cron ) {
2076              foreach ( $cron as $hook => $dings ) {
2077                  foreach ( $dings as $sig => $data ) {
2078  
2079                      $this->crons[ "$hook-$sig-$time" ] = (object) array(
2080                          'hook'     => $hook,
2081                          'time'     => $time,
2082                          'sig'      => $sig,
2083                          'args'     => $data['args'],
2084                          'schedule' => $data['schedule'],
2085                          'interval' => isset( $data['interval'] ) ? $data['interval'] : null,
2086                      );
2087  
2088                  }
2089              }
2090          }
2091      }
2092  
2093      /**
2094       * Check if any scheduled tasks have been missed.
2095       *
2096       * Returns a boolean value of `true` if a scheduled task has been missed and ends processing. If the list of
2097       * crons is an instance of WP_Error, return the instance instead of a boolean value.
2098       *
2099       * @since 5.2.0
2100       *
2101       * @return bool|WP_Error True if a cron was missed, false if not. WP_Error if the cron is set to that.
2102       */
2103  	public function has_missed_cron() {
2104          if ( is_wp_error( $this->crons ) ) {
2105              return $this->crons;
2106          }
2107  
2108          foreach ( $this->crons as $id => $cron ) {
2109              if ( ( $cron->time - time() ) < $this->timeout_missed_cron ) {
2110                  $this->last_missed_cron = $cron->hook;
2111                  return true;
2112              }
2113          }
2114  
2115          return false;
2116      }
2117  
2118      /**
2119       * Check if any scheduled tasks are late.
2120       *
2121       * Returns a boolean value of `true` if a scheduled task is late and ends processing. If the list of
2122       * crons is an instance of WP_Error, return the instance instead of a boolean value.
2123       *
2124       * @since 5.3.0
2125       *
2126       * @return bool|WP_Error True if a cron is late, false if not. WP_Error if the cron is set to that.
2127       */
2128  	public function has_late_cron() {
2129          if ( is_wp_error( $this->crons ) ) {
2130              return $this->crons;
2131          }
2132  
2133          foreach ( $this->crons as $id => $cron ) {
2134              $cron_offset = $cron->time - time();
2135              if (
2136                      $cron_offset >= $this->timeout_missed_cron &&
2137                      $cron_offset < $this->timeout_late_cron
2138                  ) {
2139                  $this->last_late_cron = $cron->hook;
2140                  return true;
2141              }
2142          }
2143  
2144          return false;
2145      }
2146  
2147      /**
2148       * Run a loopback test on our site.
2149       *
2150       * Loopbacks are what WordPress uses to communicate with itself to start up WP_Cron, scheduled posts,
2151       * make sure plugin or theme edits don't cause site failures and similar.
2152       *
2153       * @since 5.2.0
2154       *
2155       * @return object The test results.
2156       */
2157  	function can_perform_loopback() {
2158          $cookies = wp_unslash( $_COOKIE );
2159          $timeout = 10;
2160          $headers = array(
2161              'Cache-Control' => 'no-cache',
2162          );
2163          /** This filter is documented in wp-includes/class-wp-http-streams.php */
2164          $sslverify = apply_filters( 'https_local_ssl_verify', false );
2165  
2166          // Include Basic auth in loopback requests.
2167          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
2168              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
2169          }
2170  
2171          $url = admin_url();
2172  
2173          $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
2174  
2175          if ( is_wp_error( $r ) ) {
2176              return (object) array(
2177                  'status'  => 'critical',
2178                  'message' => sprintf(
2179                      '%s<br>%s',
2180                      __( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ),
2181                      sprintf(
2182                          /* translators: 1: The HTTP response code. 2: The error message returned. */
2183                          __( 'Error: [%1$s] %2$s' ),
2184                          wp_remote_retrieve_response_code( $r ),
2185                          $r->get_error_message()
2186                      )
2187                  ),
2188              );
2189          }
2190  
2191          if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
2192              return (object) array(
2193                  'status'  => 'recommended',
2194                  'message' => sprintf(
2195                      /* translators: %d: The HTTP response code returned. */
2196                      __( '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.' ),
2197                      wp_remote_retrieve_response_code( $r )
2198                  ),
2199              );
2200          }
2201  
2202          return (object) array(
2203              'status'  => 'good',
2204              'message' => __( 'The loopback request to your site completed successfully.' ),
2205          );
2206      }
2207  
2208      /**
2209       * Create a weekly cron event, if one does not already exist.
2210       *
2211       * @since 5.4.0
2212       */
2213  	public function maybe_create_scheduled_event() {
2214          if ( ! wp_next_scheduled( 'wp_site_health_scheduled_check' ) && ! wp_installing() ) {
2215              wp_schedule_event( time(), 'weekly', 'wp_site_health_scheduled_check' );
2216          }
2217      }
2218  
2219      /**
2220       * Run our scheduled event to check and update the latest site health status for the website.
2221       *
2222       * @since 5.4.0
2223       */
2224  	public function wp_cron_scheduled_check() {
2225          // Bootstrap wp-admin, as WP_Cron doesn't do this for us.
2226          require_once( trailingslashit( ABSPATH ) . 'wp-admin/includes/admin.php' );
2227  
2228          $tests = WP_Site_Health::get_tests();
2229  
2230          $results = array();
2231  
2232          $site_status = array(
2233              'good'        => 0,
2234              'recommended' => 0,
2235              'critical'    => 0,
2236          );
2237  
2238          // Don't run https test on localhost
2239          if ( 'localhost' === preg_replace( '|https?://|', '', get_site_url() ) ) {
2240              unset( $tests['direct']['https_status'] );
2241          }
2242  
2243          foreach ( $tests['direct'] as $test ) {
2244  
2245              if ( is_string( $test['test'] ) ) {
2246                  $test_function = sprintf(
2247                      'get_test_%s',
2248                      $test['test']
2249                  );
2250  
2251                  if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
2252                      $results[] = $this->perform_test( array( $this, $test_function ) );
2253                      continue;
2254                  }
2255              }
2256  
2257              if ( is_callable( $test['test'] ) ) {
2258                  $results[] = $this->perform_test( $test['test'] );
2259              }
2260          }
2261  
2262          foreach ( $tests['async'] as $test ) {
2263              if ( is_string( $test['test'] ) ) {
2264                  if ( isset( $test['has_rest'] ) && $test['has_rest'] ) {
2265                      $result_fetch = wp_remote_post(
2266                          rest_url( $test['test'] ),
2267                          array(
2268                              'body' => array(
2269                                  '_wpnonce' => wp_create_nonce( 'wp_rest' ),
2270                              ),
2271                          )
2272                      );
2273                  } else {
2274                      $result_fetch = wp_remote_post(
2275                          admin_url( 'admin-ajax.php' ),
2276                          array(
2277                              'body' => array(
2278                                  'action'   => $test['test'],
2279                                  '_wpnonce' => wp_create_nonce( 'health-check-site-status' ),
2280                              ),
2281                          )
2282                      );
2283                  }
2284  
2285                  if ( ! is_wp_error( $result_fetch ) ) {
2286                      $results[] = json_decode( wp_remote_retrieve_body( $result_fetch ) );
2287                  } else {
2288                      $results[] = array(
2289                          'status' => 'recommended',
2290                          'label'  => __( 'A test is unavailable' ),
2291                      );
2292                  }
2293              }
2294          }
2295  
2296          foreach ( $results as $result ) {
2297              if ( 'critical' === $result['status'] ) {
2298                  $site_status['critical']++;
2299              } elseif ( 'recommended' === $result['status'] ) {
2300                  $site_status['recommended']++;
2301              } else {
2302                  $site_status['good']++;
2303              }
2304          }
2305  
2306          set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) );
2307      }
2308  }


Generated: Tue Jan 21 01:00:03 2020 Cross-referenced by PHPXref 0.7.1