[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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


Generated : Thu May 9 08:20:02 2024 Cross-referenced by PHPXref