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


Generated: Sun Apr 5 01:00:03 2020 Cross-referenced by PHPXref 0.7.1