[ 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 database server is capable of using utf8mb4.
1288       *
1289       * @since 5.2.0
1290       *
1291       * @return array The test results.
1292       */
1293  	public function get_test_utf8mb4_support() {
1294          if ( ! $this->mysql_server_version ) {
1295              $this->prepare_sql_data();
1296          }
1297  
1298          $result = array(
1299              'label'       => __( 'UTF8MB4 is supported' ),
1300              'status'      => 'good',
1301              'badge'       => array(
1302                  'label' => __( 'Performance' ),
1303                  'color' => 'blue',
1304              ),
1305              'description' => sprintf(
1306                  '<p>%s</p>',
1307                  __( 'UTF8MB4 is the character set WordPress prefers for database storage because it safely supports the widest set of characters and encodings, including Emoji, enabling better support for non-English languages.' )
1308              ),
1309              'actions'     => '',
1310              'test'        => 'utf8mb4_support',
1311          );
1312  
1313          if ( ! $this->is_mariadb ) {
1314              if ( version_compare( $this->mysql_server_version, '5.5.3', '<' ) ) {
1315                  $result['status'] = 'recommended';
1316  
1317                  $result['label'] = __( 'utf8mb4 requires a MySQL update' );
1318  
1319                  $result['description'] .= sprintf(
1320                      '<p>%s</p>',
1321                      sprintf(
1322                          /* translators: %s: Version number. */
1323                          __( 'WordPress&#8217; utf8mb4 support requires MySQL version %s or greater. Please contact your server administrator.' ),
1324                          '5.5.3'
1325                      )
1326                  );
1327              } else {
1328                  $result['description'] .= sprintf(
1329                      '<p>%s</p>',
1330                      __( 'Your MySQL version supports utf8mb4.' )
1331                  );
1332              }
1333          } else { // MariaDB introduced utf8mb4 support in 5.5.0.
1334              if ( version_compare( $this->mysql_server_version, '5.5.0', '<' ) ) {
1335                  $result['status'] = 'recommended';
1336  
1337                  $result['label'] = __( 'utf8mb4 requires a MariaDB update' );
1338  
1339                  $result['description'] .= sprintf(
1340                      '<p>%s</p>',
1341                      sprintf(
1342                          /* translators: %s: Version number. */
1343                          __( 'WordPress&#8217; utf8mb4 support requires MariaDB version %s or greater. Please contact your server administrator.' ),
1344                          '5.5.0'
1345                      )
1346                  );
1347              } else {
1348                  $result['description'] .= sprintf(
1349                      '<p>%s</p>',
1350                      __( 'Your MariaDB version supports utf8mb4.' )
1351                  );
1352              }
1353          }
1354  
1355          // phpcs:ignore WordPress.DB.RestrictedFunctions.mysql_mysqli_get_client_info
1356          $mysql_client_version = mysqli_get_client_info();
1357  
1358          /*
1359           * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
1360           * mysqlnd has supported utf8mb4 since 5.0.9.
1361           */
1362          if ( str_contains( $mysql_client_version, 'mysqlnd' ) ) {
1363              $mysql_client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $mysql_client_version );
1364              if ( version_compare( $mysql_client_version, '5.0.9', '<' ) ) {
1365                  $result['status'] = 'recommended';
1366  
1367                  $result['label'] = __( 'utf8mb4 requires a newer client library' );
1368  
1369                  $result['description'] .= sprintf(
1370                      '<p>%s</p>',
1371                      sprintf(
1372                          /* translators: 1: Name of the library, 2: Number of version. */
1373                          __( 'WordPress&#8217; utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ),
1374                          'mysqlnd',
1375                          '5.0.9'
1376                      )
1377                  );
1378              }
1379          } else {
1380              if ( version_compare( $mysql_client_version, '5.5.3', '<' ) ) {
1381                  $result['status'] = 'recommended';
1382  
1383                  $result['label'] = __( 'utf8mb4 requires a newer client library' );
1384  
1385                  $result['description'] .= sprintf(
1386                      '<p>%s</p>',
1387                      sprintf(
1388                          /* translators: 1: Name of the library, 2: Number of version. */
1389                          __( 'WordPress&#8217; utf8mb4 support requires MySQL client library (%1$s) version %2$s or newer. Please contact your server administrator.' ),
1390                          'libmysql',
1391                          '5.5.3'
1392                      )
1393                  );
1394              }
1395          }
1396  
1397          return $result;
1398      }
1399  
1400      /**
1401       * Tests if the site can communicate with WordPress.org.
1402       *
1403       * @since 5.2.0
1404       *
1405       * @return array The test results.
1406       */
1407  	public function get_test_dotorg_communication() {
1408          $result = array(
1409              'label'       => __( 'Can communicate with WordPress.org' ),
1410              'status'      => '',
1411              'badge'       => array(
1412                  'label' => __( 'Security' ),
1413                  'color' => 'blue',
1414              ),
1415              'description' => sprintf(
1416                  '<p>%s</p>',
1417                  __( 'Communicating with the WordPress servers is used to check for new versions, and to both install and update WordPress core, themes or plugins.' )
1418              ),
1419              'actions'     => '',
1420              'test'        => 'dotorg_communication',
1421          );
1422  
1423          $wp_dotorg = wp_remote_get(
1424              'https://api.wordpress.org',
1425              array(
1426                  'timeout' => 10,
1427              )
1428          );
1429          if ( ! is_wp_error( $wp_dotorg ) ) {
1430              $result['status'] = 'good';
1431          } else {
1432              $result['status'] = 'critical';
1433  
1434              $result['label'] = __( 'Could not reach WordPress.org' );
1435  
1436              $result['description'] .= sprintf(
1437                  '<p>%s</p>',
1438                  sprintf(
1439                      '<span class="error"><span class="screen-reader-text">%s</span></span> %s',
1440                      /* translators: Hidden accessibility text. */
1441                      __( 'Error' ),
1442                      sprintf(
1443                          /* translators: 1: The IP address WordPress.org resolves to. 2: The error returned by the lookup. */
1444                          __( 'Your site is unable to reach WordPress.org at %1$s, and returned the error: %2$s' ),
1445                          gethostbyname( 'api.wordpress.org' ),
1446                          $wp_dotorg->get_error_message()
1447                      )
1448                  )
1449              );
1450  
1451              $result['actions'] = sprintf(
1452                  '<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>',
1453                  /* translators: Localized Support reference. */
1454                  esc_url( __( 'https://wordpress.org/support/forums/' ) ),
1455                  __( 'Get help resolving this issue.' ),
1456                  /* translators: Hidden accessibility text. */
1457                  __( '(opens in a new tab)' )
1458              );
1459          }
1460  
1461          return $result;
1462      }
1463  
1464      /**
1465       * Tests if debug information is enabled.
1466       *
1467       * When WP_DEBUG is enabled, errors and information may be disclosed to site visitors,
1468       * or logged to a publicly accessible file.
1469       *
1470       * Debugging is also frequently left enabled after looking for errors on a site,
1471       * as site owners do not understand the implications of this.
1472       *
1473       * @since 5.2.0
1474       *
1475       * @return array The test results.
1476       */
1477  	public function get_test_is_in_debug_mode() {
1478          $result = array(
1479              'label'       => __( 'Your site is not set to output debug information' ),
1480              'status'      => 'good',
1481              'badge'       => array(
1482                  'label' => __( 'Security' ),
1483                  'color' => 'blue',
1484              ),
1485              'description' => sprintf(
1486                  '<p>%s</p>',
1487                  __( '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.' )
1488              ),
1489              'actions'     => sprintf(
1490                  '<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>',
1491                  /* translators: Documentation explaining debugging in WordPress. */
1492                  esc_url( __( 'https://developer.wordpress.org/advanced-administration/debug/debug-wordpress/' ) ),
1493                  __( 'Learn more about debugging in WordPress.' ),
1494                  /* translators: Hidden accessibility text. */
1495                  __( '(opens in a new tab)' )
1496              ),
1497              'test'        => 'is_in_debug_mode',
1498          );
1499  
1500          if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
1501              if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
1502                  $result['label'] = __( 'Your site is set to log errors to a potentially public file' );
1503  
1504                  $result['status'] = str_starts_with( ini_get( 'error_log' ), ABSPATH ) ? 'critical' : 'recommended';
1505  
1506                  $result['description'] .= sprintf(
1507                      '<p>%s</p>',
1508                      sprintf(
1509                          /* translators: %s: WP_DEBUG_LOG */
1510                          __( '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.' ),
1511                          '<code>WP_DEBUG_LOG</code>'
1512                      )
1513                  );
1514              }
1515  
1516              if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) {
1517                  $result['label'] = __( 'Your site is set to display errors to site visitors' );
1518  
1519                  $result['status'] = 'critical';
1520  
1521                  // On development environments, set the status to recommended.
1522                  if ( $this->is_development_environment() ) {
1523                      $result['status'] = 'recommended';
1524                  }
1525  
1526                  $result['description'] .= sprintf(
1527                      '<p>%s</p>',
1528                      sprintf(
1529                          /* translators: 1: WP_DEBUG_DISPLAY, 2: WP_DEBUG */
1530                          __( '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.' ),
1531                          '<code>WP_DEBUG_DISPLAY</code>',
1532                          '<code>WP_DEBUG</code>'
1533                      )
1534                  );
1535              }
1536          }
1537  
1538          return $result;
1539      }
1540  
1541      /**
1542       * Tests if the site is serving content over HTTPS.
1543       *
1544       * Many sites have varying degrees of HTTPS support, the most common of which is sites that have it
1545       * enabled, but only if you visit the right site address.
1546       *
1547       * @since 5.2.0
1548       * @since 5.7.0 Updated to rely on {@see wp_is_using_https()} and {@see wp_is_https_supported()}.
1549       *
1550       * @return array The test results.
1551       */
1552  	public function get_test_https_status() {
1553          /*
1554           * Check HTTPS detection results.
1555           */
1556          $errors = wp_get_https_detection_errors();
1557  
1558          $default_update_url = wp_get_default_update_https_url();
1559  
1560          $result = array(
1561              'label'       => __( 'Your website is using an active HTTPS connection' ),
1562              'status'      => 'good',
1563              'badge'       => array(
1564                  'label' => __( 'Security' ),
1565                  'color' => 'blue',
1566              ),
1567              'description' => sprintf(
1568                  '<p>%s</p>',
1569                  __( '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.' )
1570              ),
1571              'actions'     => sprintf(
1572                  '<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>',
1573                  esc_url( $default_update_url ),
1574                  __( 'Learn more about why you should use HTTPS' ),
1575                  /* translators: Hidden accessibility text. */
1576                  __( '(opens in a new tab)' )
1577              ),
1578              'test'        => 'https_status',
1579          );
1580  
1581          if ( ! wp_is_using_https() ) {
1582              /*
1583               * If the website is not using HTTPS, provide more information
1584               * about whether it is supported and how it can be enabled.
1585               */
1586              $result['status'] = 'recommended';
1587              $result['label']  = __( 'Your website does not use HTTPS' );
1588  
1589              if ( wp_is_site_url_using_https() ) {
1590                  if ( is_ssl() ) {
1591                      $result['description'] = sprintf(
1592                          '<p>%s</p>',
1593                          sprintf(
1594                              /* translators: %s: URL to Settings > General > Site Address. */
1595                              __( 'You are accessing this website using HTTPS, but your <a href="%s">Site Address</a> is not set up to use HTTPS by default.' ),
1596                              esc_url( admin_url( 'options-general.php' ) . '#home' )
1597                          )
1598                      );
1599                  } else {
1600                      $result['description'] = sprintf(
1601                          '<p>%s</p>',
1602                          sprintf(
1603                              /* translators: %s: URL to Settings > General > Site Address. */
1604                              __( 'Your <a href="%s">Site Address</a> is not set up to use HTTPS.' ),
1605                              esc_url( admin_url( 'options-general.php' ) . '#home' )
1606                          )
1607                      );
1608                  }
1609              } else {
1610                  if ( is_ssl() ) {
1611                      $result['description'] = sprintf(
1612                          '<p>%s</p>',
1613                          sprintf(
1614                              /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
1615                              __( '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.' ),
1616                              esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
1617                              esc_url( admin_url( 'options-general.php' ) . '#home' )
1618                          )
1619                      );
1620                  } else {
1621                      $result['description'] = sprintf(
1622                          '<p>%s</p>',
1623                          sprintf(
1624                              /* translators: 1: URL to Settings > General > WordPress Address, 2: URL to Settings > General > Site Address. */
1625                              __( 'Your <a href="%1$s">WordPress Address</a> and <a href="%2$s">Site Address</a> are not set up to use HTTPS.' ),
1626                              esc_url( admin_url( 'options-general.php' ) . '#siteurl' ),
1627                              esc_url( admin_url( 'options-general.php' ) . '#home' )
1628                          )
1629                      );
1630                  }
1631              }
1632  
1633              if ( wp_is_https_supported() ) {
1634                  $result['description'] .= sprintf(
1635                      '<p>%s</p>',
1636                      __( 'HTTPS is already supported for your website.' )
1637                  );
1638  
1639                  if ( defined( 'WP_HOME' ) || defined( 'WP_SITEURL' ) ) {
1640                      $result['description'] .= sprintf(
1641                          '<p>%s</p>',
1642                          sprintf(
1643                              /* translators: 1: wp-config.php, 2: WP_HOME, 3: WP_SITEURL */
1644                              __( '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.' ),
1645                              '<code>wp-config.php</code>',
1646                              '<code>WP_HOME</code>',
1647                              '<code>WP_SITEURL</code>'
1648                          )
1649                      );
1650                  } elseif ( current_user_can( 'update_https' ) ) {
1651                      $default_direct_update_url = add_query_arg( 'action', 'update_https', wp_nonce_url( admin_url( 'site-health.php' ), 'wp_update_https' ) );
1652                      $direct_update_url         = wp_get_direct_update_https_url();
1653  
1654                      if ( ! empty( $direct_update_url ) ) {
1655                          $result['actions'] = sprintf(
1656                              '<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>',
1657                              esc_url( $direct_update_url ),
1658                              __( 'Update your site to use HTTPS' ),
1659                              /* translators: Hidden accessibility text. */
1660                              __( '(opens in a new tab)' )
1661                          );
1662                      } else {
1663                          $result['actions'] = sprintf(
1664                              '<p class="button-container"><a class="button button-primary" href="%1$s">%2$s</a></p>',
1665                              esc_url( $default_direct_update_url ),
1666                              __( 'Update your site to use HTTPS' )
1667                          );
1668                      }
1669                  }
1670              } else {
1671                  // If host-specific "Update HTTPS" URL is provided, include a link.
1672                  $update_url = wp_get_update_https_url();
1673                  if ( $update_url !== $default_update_url ) {
1674                      $result['description'] .= sprintf(
1675                          '<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>',
1676                          esc_url( $update_url ),
1677                          __( 'Talk to your web host about supporting HTTPS for your website.' ),
1678                          /* translators: Hidden accessibility text. */
1679                          __( '(opens in a new tab)' )
1680                      );
1681                  } else {
1682                      $result['description'] .= sprintf(
1683                          '<p>%s</p>',
1684                          __( 'Talk to your web host about supporting HTTPS for your website.' )
1685                      );
1686                  }
1687              }
1688          }
1689  
1690          return $result;
1691      }
1692  
1693      /**
1694       * Checks if the HTTP API can handle SSL/TLS requests.
1695       *
1696       * @since 5.2.0
1697       *
1698       * @return array The test result.
1699       */
1700  	public function get_test_ssl_support() {
1701          $result = array(
1702              'label'       => '',
1703              'status'      => '',
1704              'badge'       => array(
1705                  'label' => __( 'Security' ),
1706                  'color' => 'blue',
1707              ),
1708              'description' => sprintf(
1709                  '<p>%s</p>',
1710                  __( 'Securely communicating between servers are needed for transactions such as fetching files, conducting sales on store sites, and much more.' )
1711              ),
1712              'actions'     => '',
1713              'test'        => 'ssl_support',
1714          );
1715  
1716          $supports_https = wp_http_supports( array( 'ssl' ) );
1717  
1718          if ( $supports_https ) {
1719              $result['status'] = 'good';
1720  
1721              $result['label'] = __( 'Your site can communicate securely with other services' );
1722          } else {
1723              $result['status'] = 'critical';
1724  
1725              $result['label'] = __( 'Your site is unable to communicate securely with other services' );
1726  
1727              $result['description'] .= sprintf(
1728                  '<p>%s</p>',
1729                  __( 'Talk to your web host about OpenSSL support for PHP.' )
1730              );
1731          }
1732  
1733          return $result;
1734      }
1735  
1736      /**
1737       * Tests if scheduled events run as intended.
1738       *
1739       * If scheduled events are not running, this may indicate something with WP_Cron is not working
1740       * as intended, or that there are orphaned events hanging around from older code.
1741       *
1742       * @since 5.2.0
1743       *
1744       * @return array The test results.
1745       */
1746  	public function get_test_scheduled_events() {
1747          $result = array(
1748              'label'       => __( 'Scheduled events are running' ),
1749              'status'      => 'good',
1750              'badge'       => array(
1751                  'label' => __( 'Performance' ),
1752                  'color' => 'blue',
1753              ),
1754              'description' => sprintf(
1755                  '<p>%s</p>',
1756                  __( '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.' )
1757              ),
1758              'actions'     => '',
1759              'test'        => 'scheduled_events',
1760          );
1761  
1762          $this->wp_schedule_test_init();
1763  
1764          if ( is_wp_error( $this->has_missed_cron() ) ) {
1765              $result['status'] = 'critical';
1766  
1767              $result['label'] = __( 'It was not possible to check your scheduled events' );
1768  
1769              $result['description'] = sprintf(
1770                  '<p>%s</p>',
1771                  sprintf(
1772                      /* translators: %s: The error message returned while from the cron scheduler. */
1773                      __( 'While trying to test your site&#8217;s scheduled events, the following error was returned: %s' ),
1774                      $this->has_missed_cron()->get_error_message()
1775                  )
1776              );
1777          } elseif ( $this->has_missed_cron() ) {
1778              $result['status'] = 'recommended';
1779  
1780              $result['label'] = __( 'A scheduled event has failed' );
1781  
1782              $result['description'] = sprintf(
1783                  '<p>%s</p>',
1784                  sprintf(
1785                      /* translators: %s: The name of the failed cron event. */
1786                      __( '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.' ),
1787                      $this->last_missed_cron
1788                  )
1789              );
1790          } elseif ( $this->has_late_cron() ) {
1791              $result['status'] = 'recommended';
1792  
1793              $result['label'] = __( 'A scheduled event is late' );
1794  
1795              $result['description'] = sprintf(
1796                  '<p>%s</p>',
1797                  sprintf(
1798                      /* translators: %s: The name of the late cron event. */
1799                      __( '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.' ),
1800                      $this->last_late_cron
1801                  )
1802              );
1803          }
1804  
1805          return $result;
1806      }
1807  
1808      /**
1809       * Tests if WordPress can run automated background updates.
1810       *
1811       * Background updates in WordPress are primarily used for minor releases and security updates.
1812       * It's important to either have these working, or be aware that they are intentionally disabled
1813       * for whatever reason.
1814       *
1815       * @since 5.2.0
1816       *
1817       * @return array The test results.
1818       */
1819  	public function get_test_background_updates() {
1820          $result = array(
1821              'label'       => __( 'Background updates are working' ),
1822              'status'      => 'good',
1823              'badge'       => array(
1824                  'label' => __( 'Security' ),
1825                  'color' => 'blue',
1826              ),
1827              'description' => sprintf(
1828                  '<p>%s</p>',
1829                  __( 'Background updates ensure that WordPress can auto-update if a security update is released for the version you are currently using.' )
1830              ),
1831              'actions'     => '',
1832              'test'        => 'background_updates',
1833          );
1834  
1835          if ( ! class_exists( 'WP_Site_Health_Auto_Updates' ) ) {
1836              require_once  ABSPATH . 'wp-admin/includes/class-wp-site-health-auto-updates.php';
1837          }
1838  
1839          /*
1840           * Run the auto-update tests in a separate class,
1841           * as there are many considerations to be made.
1842           */
1843          $automatic_updates = new WP_Site_Health_Auto_Updates();
1844          $tests             = $automatic_updates->run_tests();
1845  
1846          $output = '<ul>';
1847  
1848          foreach ( $tests as $test ) {
1849              /* translators: Hidden accessibility text. */
1850              $severity_string = __( 'Passed' );
1851  
1852              if ( 'fail' === $test->severity ) {
1853                  $result['label'] = __( 'Background updates are not working as expected' );
1854  
1855                  $result['status'] = 'critical';
1856  
1857                  /* translators: Hidden accessibility text. */
1858                  $severity_string = __( 'Error' );
1859              }
1860  
1861              if ( 'warning' === $test->severity && 'good' === $result['status'] ) {
1862                  $result['label'] = __( 'Background updates may not be working properly' );
1863  
1864                  $result['status'] = 'recommended';
1865  
1866                  /* translators: Hidden accessibility text. */
1867                  $severity_string = __( 'Warning' );
1868              }
1869  
1870              $output .= sprintf(
1871                  '<li><span class="dashicons %s"><span class="screen-reader-text">%s</span></span> %s</li>',
1872                  esc_attr( $test->severity ),
1873                  $severity_string,
1874                  $test->description
1875              );
1876          }
1877  
1878          $output .= '</ul>';
1879  
1880          if ( 'good' !== $result['status'] ) {
1881              $result['description'] .= $output;
1882          }
1883  
1884          return $result;
1885      }
1886  
1887      /**
1888       * Tests if plugin and theme auto-updates appear to be configured correctly.
1889       *
1890       * @since 5.5.0
1891       *
1892       * @return array The test results.
1893       */
1894  	public function get_test_plugin_theme_auto_updates() {
1895          $result = array(
1896              'label'       => __( 'Plugin and theme auto-updates appear to be configured correctly' ),
1897              'status'      => 'good',
1898              'badge'       => array(
1899                  'label' => __( 'Security' ),
1900                  'color' => 'blue',
1901              ),
1902              'description' => sprintf(
1903                  '<p>%s</p>',
1904                  __( 'Plugin and theme auto-updates ensure that the latest versions are always installed.' )
1905              ),
1906              'actions'     => '',
1907              'test'        => 'plugin_theme_auto_updates',
1908          );
1909  
1910          $check_plugin_theme_updates = $this->detect_plugin_theme_auto_update_issues();
1911  
1912          $result['status'] = $check_plugin_theme_updates->status;
1913  
1914          if ( 'good' !== $result['status'] ) {
1915              $result['label'] = __( 'Your site may have problems auto-updating plugins and themes' );
1916  
1917              $result['description'] .= sprintf(
1918                  '<p>%s</p>',
1919                  $check_plugin_theme_updates->message
1920              );
1921          }
1922  
1923          return $result;
1924      }
1925  
1926      /**
1927       * Tests available disk space for updates.
1928       *
1929       * @since 6.3.0
1930       *
1931       * @return array The test results.
1932       */
1933  	public function get_test_available_updates_disk_space() {
1934          $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR . '/upgrade/' ) : false;
1935  
1936          $result = array(
1937              'label'       => __( 'Disk space available to safely perform updates' ),
1938              'status'      => 'good',
1939              'badge'       => array(
1940                  'label' => __( 'Security' ),
1941                  'color' => 'blue',
1942              ),
1943              'description' => sprintf(
1944                  /* translators: %s: Available disk space in MB or GB. */
1945                  '<p>' . __( '%s available disk space was detected, update routines can be performed safely.' ) . '</p>',
1946                  size_format( $available_space )
1947              ),
1948              'actions'     => '',
1949              'test'        => 'available_updates_disk_space',
1950          );
1951  
1952          if ( false === $available_space ) {
1953              $result['description'] = __( 'Could not determine available disk space for updates.' );
1954              $result['status']      = 'recommended';
1955          } elseif ( $available_space < 20 * MB_IN_BYTES ) {
1956              $result['description'] = __( 'Available disk space is critically low, less than 20 MB available. Proceed with caution, updates may fail.' );
1957              $result['status']      = 'critical';
1958          } elseif ( $available_space < 100 * MB_IN_BYTES ) {
1959              $result['description'] = __( 'Available disk space is low, less than 100 MB available.' );
1960              $result['status']      = 'recommended';
1961          }
1962  
1963          return $result;
1964      }
1965  
1966      /**
1967       * Tests if plugin and theme temporary backup directories are writable or can be created.
1968       *
1969       * @since 6.3.0
1970       *
1971       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1972       *
1973       * @return array The test results.
1974       */
1975  	public function get_test_update_temp_backup_writable() {
1976          global $wp_filesystem;
1977  
1978          $result = array(
1979              'label'       => __( 'Plugin and theme temporary backup directory is writable' ),
1980              'status'      => 'good',
1981              'badge'       => array(
1982                  'label' => __( 'Security' ),
1983                  'color' => 'blue',
1984              ),
1985              'description' => sprintf(
1986                  /* translators: %s: wp-content/upgrade-temp-backup */
1987                  '<p>' . __( 'The %s directory used to improve the stability of plugin and theme updates is writable.' ) . '</p>',
1988                  '<code>wp-content/upgrade-temp-backup</code>'
1989              ),
1990              'actions'     => '',
1991              'test'        => 'update_temp_backup_writable',
1992          );
1993  
1994          if ( ! function_exists( 'WP_Filesystem' ) ) {
1995              require_once  ABSPATH . '/wp-admin/includes/file.php';
1996          }
1997  
1998          ob_start();
1999          $credentials = request_filesystem_credentials( '' );
2000          ob_end_clean();
2001  
2002          if ( false === $credentials || ! WP_Filesystem( $credentials ) ) {
2003              $result['status']      = 'recommended';
2004              $result['label']       = __( 'Could not access filesystem' );
2005              $result['description'] = __( 'Unable to connect to the filesystem. Please confirm your credentials.' );
2006              return $result;
2007          }
2008  
2009          $wp_content = $wp_filesystem->wp_content_dir();
2010  
2011          if ( ! $wp_content ) {
2012              $result['status']      = 'critical';
2013              $result['label']       = __( 'Unable to locate WordPress content directory' );
2014              $result['description'] = sprintf(
2015                  /* translators: %s: wp-content */
2016                  '<p>' . __( 'The %s directory cannot be located.' ) . '</p>',
2017                  '<code>wp-content</code>'
2018              );
2019              return $result;
2020          }
2021  
2022          $upgrade_dir_exists      = $wp_filesystem->is_dir( "$wp_content/upgrade" );
2023          $upgrade_dir_is_writable = $wp_filesystem->is_writable( "$wp_content/upgrade" );
2024          $backup_dir_exists       = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup" );
2025          $backup_dir_is_writable  = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup" );
2026  
2027          $plugins_dir_exists      = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup/plugins" );
2028          $plugins_dir_is_writable = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup/plugins" );
2029          $themes_dir_exists       = $wp_filesystem->is_dir( "$wp_content/upgrade-temp-backup/themes" );
2030          $themes_dir_is_writable  = $wp_filesystem->is_writable( "$wp_content/upgrade-temp-backup/themes" );
2031  
2032          if ( $plugins_dir_exists && ! $plugins_dir_is_writable && $themes_dir_exists && ! $themes_dir_is_writable ) {
2033              $result['status']      = 'critical';
2034              $result['label']       = __( 'Plugin and theme temporary backup directories exist but are not writable' );
2035              $result['description'] = sprintf(
2036                  /* translators: 1: wp-content/upgrade-temp-backup/plugins, 2: wp-content/upgrade-temp-backup/themes. */
2037                  '<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>',
2038                  '<code>wp-content/upgrade-temp-backup/plugins</code>',
2039                  '<code>wp-content/upgrade-temp-backup/themes</code>'
2040              );
2041              return $result;
2042          }
2043  
2044          if ( $plugins_dir_exists && ! $plugins_dir_is_writable ) {
2045              $result['status']      = 'critical';
2046              $result['label']       = __( 'Plugin temporary backup directory exists but is not writable' );
2047              $result['description'] = sprintf(
2048                  /* translators: %s: wp-content/upgrade-temp-backup/plugins */
2049                  '<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>',
2050                  '<code>wp-content/upgrade-temp-backup/plugins</code>'
2051              );
2052              return $result;
2053          }
2054  
2055          if ( $themes_dir_exists && ! $themes_dir_is_writable ) {
2056              $result['status']      = 'critical';
2057              $result['label']       = __( 'Theme temporary backup directory exists but is not writable' );
2058              $result['description'] = sprintf(
2059                  /* translators: %s: wp-content/upgrade-temp-backup/themes */
2060                  '<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>',
2061                  '<code>wp-content/upgrade-temp-backup/themes</code>'
2062              );
2063              return $result;
2064          }
2065  
2066          if ( ( ! $plugins_dir_exists || ! $themes_dir_exists ) && $backup_dir_exists && ! $backup_dir_is_writable ) {
2067              $result['status']      = 'critical';
2068              $result['label']       = __( 'The temporary backup directory exists but is not writable' );
2069              $result['description'] = sprintf(
2070                  /* translators: %s: wp-content/upgrade-temp-backup */
2071                  '<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>',
2072                  '<code>wp-content/upgrade-temp-backup</code>'
2073              );
2074              return $result;
2075          }
2076  
2077          if ( ! $backup_dir_exists && $upgrade_dir_exists && ! $upgrade_dir_is_writable ) {
2078              $result['status']      = 'critical';
2079              $result['label']       = __( 'The upgrade directory exists but is not writable' );
2080              $result['description'] = sprintf(
2081                  /* translators: %s: wp-content/upgrade */
2082                  '<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>',
2083                  '<code>wp-content/upgrade</code>'
2084              );
2085              return $result;
2086          }
2087  
2088          if ( ! $upgrade_dir_exists && ! $wp_filesystem->is_writable( $wp_content ) ) {
2089              $result['status']      = 'critical';
2090              $result['label']       = __( 'The upgrade directory cannot be created' );
2091              $result['description'] = sprintf(
2092                  /* translators: 1: wp-content/upgrade, 2: wp-content. */
2093                  '<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>',
2094                  '<code>wp-content/upgrade</code>',
2095                  '<code>wp-content</code>'
2096              );
2097              return $result;
2098          }
2099  
2100          return $result;
2101      }
2102  
2103      /**
2104       * Tests if loopbacks work as expected.
2105       *
2106       * A loopback is when WordPress queries itself, for example to start a new WP_Cron instance,
2107       * or when editing a plugin or theme. This has shown itself to be a recurring issue,
2108       * as code can very easily break this interaction.
2109       *
2110       * @since 5.2.0
2111       *
2112       * @return array The test results.
2113       */
2114  	public function get_test_loopback_requests() {
2115          $result = array(
2116              'label'       => __( 'Your site can perform loopback requests' ),
2117              'status'      => 'good',
2118              'badge'       => array(
2119                  'label' => __( 'Performance' ),
2120                  'color' => 'blue',
2121              ),
2122              'description' => sprintf(
2123                  '<p>%s</p>',
2124                  __( '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.' )
2125              ),
2126              'actions'     => '',
2127              'test'        => 'loopback_requests',
2128          );
2129  
2130          $check_loopback = $this->can_perform_loopback();
2131  
2132          $result['status'] = $check_loopback->status;
2133  
2134          if ( 'good' !== $result['status'] ) {
2135              $result['label'] = __( 'Your site could not complete a loopback request' );
2136  
2137              $result['description'] .= sprintf(
2138                  '<p>%s</p>',
2139                  $check_loopback->message
2140              );
2141          }
2142  
2143          return $result;
2144      }
2145  
2146      /**
2147       * Tests if HTTP requests are blocked.
2148       *
2149       * It's possible to block all outgoing communication (with the possibility of allowing certain
2150       * hosts) via the HTTP API. This may create problems for users as many features are running as
2151       * services these days.
2152       *
2153       * @since 5.2.0
2154       *
2155       * @return array The test results.
2156       */
2157  	public function get_test_http_requests() {
2158          $result = array(
2159              'label'       => __( 'HTTP requests seem to be working as expected' ),
2160              'status'      => 'good',
2161              'badge'       => array(
2162                  'label' => __( 'Performance' ),
2163                  'color' => 'blue',
2164              ),
2165              'description' => sprintf(
2166                  '<p>%s</p>',
2167                  __( '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.' )
2168              ),
2169              'actions'     => '',
2170              'test'        => 'http_requests',
2171          );
2172  
2173          $blocked = false;
2174          $hosts   = array();
2175  
2176          if ( defined( 'WP_HTTP_BLOCK_EXTERNAL' ) && WP_HTTP_BLOCK_EXTERNAL ) {
2177              $blocked = true;
2178          }
2179  
2180          if ( defined( 'WP_ACCESSIBLE_HOSTS' ) ) {
2181              $hosts = explode( ',', WP_ACCESSIBLE_HOSTS );
2182          }
2183  
2184          if ( $blocked && 0 === count( $hosts ) ) {
2185              $result['status'] = 'critical';
2186  
2187              $result['label'] = __( 'HTTP requests are blocked' );
2188  
2189              $result['description'] .= sprintf(
2190                  '<p>%s</p>',
2191                  sprintf(
2192                      /* translators: %s: Name of the constant used. */
2193                      __( 'HTTP requests have been blocked by the %s constant, with no allowed hosts.' ),
2194                      '<code>WP_HTTP_BLOCK_EXTERNAL</code>'
2195                  )
2196              );
2197          }
2198  
2199          if ( $blocked && 0 < count( $hosts ) ) {
2200              $result['status'] = 'recommended';
2201  
2202              $result['label'] = __( 'HTTP requests are partially blocked' );
2203  
2204              $result['description'] .= sprintf(
2205                  '<p>%s</p>',
2206                  sprintf(
2207                      /* translators: 1: Name of the constant used. 2: List of allowed hostnames. */
2208                      __( 'HTTP requests have been blocked by the %1$s constant, with some allowed hosts: %2$s.' ),
2209                      '<code>WP_HTTP_BLOCK_EXTERNAL</code>',
2210                      implode( ',', $hosts )
2211                  )
2212              );
2213          }
2214  
2215          return $result;
2216      }
2217  
2218      /**
2219       * Tests if the REST API is accessible.
2220       *
2221       * Various security measures may block the REST API from working, or it may have been disabled in general.
2222       * This is required for the new block editor to work, so we explicitly test for this.
2223       *
2224       * @since 5.2.0
2225       *
2226       * @return array The test results.
2227       */
2228  	public function get_test_rest_availability() {
2229          $result = array(
2230              'label'       => __( 'The REST API is available' ),
2231              'status'      => 'good',
2232              'badge'       => array(
2233                  'label' => __( 'Performance' ),
2234                  'color' => 'blue',
2235              ),
2236              'description' => sprintf(
2237                  '<p>%s</p>',
2238                  __( '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.' )
2239              ),
2240              'actions'     => '',
2241              'test'        => 'rest_availability',
2242          );
2243  
2244          $cookies = wp_unslash( $_COOKIE );
2245          $timeout = 10; // 10 seconds.
2246          $headers = array(
2247              'Cache-Control' => 'no-cache',
2248              'X-WP-Nonce'    => wp_create_nonce( 'wp_rest' ),
2249          );
2250          /** This filter is documented in wp-includes/class-wp-http-streams.php */
2251          $sslverify = apply_filters( 'https_local_ssl_verify', false );
2252  
2253          // Include Basic auth in loopback requests.
2254          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
2255              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
2256          }
2257  
2258          $url = rest_url( 'wp/v2/types/post' );
2259  
2260          // The context for this is editing with the new block editor.
2261          $url = add_query_arg(
2262              array(
2263                  'context' => 'edit',
2264              ),
2265              $url
2266          );
2267  
2268          $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
2269  
2270          if ( is_wp_error( $r ) ) {
2271              $result['status'] = 'critical';
2272  
2273              $result['label'] = __( 'The REST API encountered an error' );
2274  
2275              $result['description'] .= sprintf(
2276                  '<p>%s</p><p>%s<br>%s</p>',
2277                  __( 'When testing the REST API, an error was encountered:' ),
2278                  sprintf(
2279                      // translators: %s: The REST API URL.
2280                      __( 'REST API Endpoint: %s' ),
2281                      $url
2282                  ),
2283                  sprintf(
2284                      // translators: 1: The WordPress error code. 2: The WordPress error message.
2285                      __( 'REST API Response: (%1$s) %2$s' ),
2286                      $r->get_error_code(),
2287                      $r->get_error_message()
2288                  )
2289              );
2290          } elseif ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
2291              $result['status'] = 'recommended';
2292  
2293              $result['label'] = __( 'The REST API encountered an unexpected result' );
2294  
2295              $result['description'] .= sprintf(
2296                  '<p>%s</p><p>%s<br>%s</p>',
2297                  __( 'When testing the REST API, an unexpected result was returned:' ),
2298                  sprintf(
2299                      // translators: %s: The REST API URL.
2300                      __( 'REST API Endpoint: %s' ),
2301                      $url
2302                  ),
2303                  sprintf(
2304                      // translators: 1: The WordPress error code. 2: The HTTP status code error message.
2305                      __( 'REST API Response: (%1$s) %2$s' ),
2306                      wp_remote_retrieve_response_code( $r ),
2307                      wp_remote_retrieve_response_message( $r )
2308                  )
2309              );
2310          } else {
2311              $json = json_decode( wp_remote_retrieve_body( $r ), true );
2312  
2313              if ( false !== $json && ! isset( $json['capabilities'] ) ) {
2314                  $result['status'] = 'recommended';
2315  
2316                  $result['label'] = __( 'The REST API did not behave correctly' );
2317  
2318                  $result['description'] .= sprintf(
2319                      '<p>%s</p>',
2320                      sprintf(
2321                          /* translators: %s: The name of the query parameter being tested. */
2322                          __( 'The REST API did not process the %s query parameter correctly.' ),
2323                          '<code>context</code>'
2324                      )
2325                  );
2326              }
2327          }
2328  
2329          return $result;
2330      }
2331  
2332      /**
2333       * Tests if 'file_uploads' directive in PHP.ini is turned off.
2334       *
2335       * @since 5.5.0
2336       *
2337       * @return array The test results.
2338       */
2339  	public function get_test_file_uploads() {
2340          $result = array(
2341              'label'       => __( 'Files can be uploaded' ),
2342              'status'      => 'good',
2343              'badge'       => array(
2344                  'label' => __( 'Performance' ),
2345                  'color' => 'blue',
2346              ),
2347              'description' => sprintf(
2348                  '<p>%s</p>',
2349                  sprintf(
2350                      /* translators: 1: file_uploads, 2: php.ini */
2351                      __( 'The %1$s directive in %2$s determines if uploading files is allowed on your site.' ),
2352                      '<code>file_uploads</code>',
2353                      '<code>php.ini</code>'
2354                  )
2355              ),
2356              'actions'     => '',
2357              'test'        => 'file_uploads',
2358          );
2359  
2360          if ( ! function_exists( 'ini_get' ) ) {
2361              $result['status']       = 'critical';
2362              $result['description'] .= sprintf(
2363                  /* translators: %s: ini_get() */
2364                  __( 'The %s function has been disabled, some media settings are unavailable because of this.' ),
2365                  '<code>ini_get()</code>'
2366              );
2367              return $result;
2368          }
2369  
2370          if ( empty( ini_get( 'file_uploads' ) ) ) {
2371              $result['status']       = 'critical';
2372              $result['description'] .= sprintf(
2373                  '<p>%s</p>',
2374                  sprintf(
2375                      /* translators: 1: file_uploads, 2: 0 */
2376                      __( '%1$s is set to %2$s. You won\'t be able to upload files on your site.' ),
2377                      '<code>file_uploads</code>',
2378                      '<code>0</code>'
2379                  )
2380              );
2381              return $result;
2382          }
2383  
2384          $post_max_size       = ini_get( 'post_max_size' );
2385          $upload_max_filesize = ini_get( 'upload_max_filesize' );
2386  
2387          if ( wp_convert_hr_to_bytes( $post_max_size ) < wp_convert_hr_to_bytes( $upload_max_filesize ) ) {
2388              $result['label'] = sprintf(
2389                  /* translators: 1: post_max_size, 2: upload_max_filesize */
2390                  __( 'The "%1$s" value is smaller than "%2$s"' ),
2391                  'post_max_size',
2392                  'upload_max_filesize'
2393              );
2394              $result['status'] = 'recommended';
2395  
2396              if ( 0 === wp_convert_hr_to_bytes( $post_max_size ) ) {
2397                  $result['description'] = sprintf(
2398                      '<p>%s</p>',
2399                      sprintf(
2400                          /* translators: 1: post_max_size, 2: upload_max_filesize */
2401                          __( '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.' ),
2402                          '<code>post_max_size</code>',
2403                          '<code>upload_max_filesize</code>'
2404                      )
2405                  );
2406              } else {
2407                  $result['description'] = sprintf(
2408                      '<p>%s</p>',
2409                      sprintf(
2410                          /* translators: 1: post_max_size, 2: upload_max_filesize */
2411                          __( 'The setting for %1$s is smaller than %2$s, this could cause some problems when trying to upload files.' ),
2412                          '<code>post_max_size</code>',
2413                          '<code>upload_max_filesize</code>'
2414                      )
2415                  );
2416              }
2417  
2418              return $result;
2419          }
2420  
2421          return $result;
2422      }
2423  
2424      /**
2425       * Tests if the Authorization header has the expected values.
2426       *
2427       * @since 5.6.0
2428       *
2429       * @return array
2430       */
2431  	public function get_test_authorization_header() {
2432          $result = array(
2433              'label'       => __( 'The Authorization header is working as expected' ),
2434              'status'      => 'good',
2435              'badge'       => array(
2436                  'label' => __( 'Security' ),
2437                  'color' => 'blue',
2438              ),
2439              'description' => sprintf(
2440                  '<p>%s</p>',
2441                  __( '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.' )
2442              ),
2443              'actions'     => '',
2444              'test'        => 'authorization_header',
2445          );
2446  
2447          if ( ! isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
2448              $result['label'] = __( 'The authorization header is missing' );
2449          } elseif ( 'user' !== $_SERVER['PHP_AUTH_USER'] || 'pwd' !== $_SERVER['PHP_AUTH_PW'] ) {
2450              $result['label'] = __( 'The authorization header is invalid' );
2451          } else {
2452              return $result;
2453          }
2454  
2455          $result['status']       = 'recommended';
2456          $result['description'] .= sprintf(
2457              '<p>%s</p>',
2458              __( 'If you are still seeing this warning after having tried the actions below, you may need to contact your hosting provider for further assistance.' )
2459          );
2460  
2461          if ( ! function_exists( 'got_mod_rewrite' ) ) {
2462              require_once  ABSPATH . 'wp-admin/includes/misc.php';
2463          }
2464  
2465          if ( got_mod_rewrite() ) {
2466              $result['actions'] .= sprintf(
2467                  '<p><a href="%s">%s</a></p>',
2468                  esc_url( admin_url( 'options-permalink.php' ) ),
2469                  __( 'Flush permalinks' )
2470              );
2471          } else {
2472              $result['actions'] .= sprintf(
2473                  '<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>',
2474                  __( 'https://developer.wordpress.org/rest-api/frequently-asked-questions/#why-is-authentication-not-working' ),
2475                  __( 'Learn how to configure the Authorization header.' ),
2476                  /* translators: Hidden accessibility text. */
2477                  __( '(opens in a new tab)' )
2478              );
2479          }
2480  
2481          return $result;
2482      }
2483  
2484      /**
2485       * Tests if a full page cache is available.
2486       *
2487       * @since 6.1.0
2488       *
2489       * @return array The test result.
2490       */
2491  	public function get_test_page_cache() {
2492          $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>';
2493          $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>';
2494          $description .= '<code>' . implode( '</code>, <code>', array_keys( $this->get_page_cache_headers() ) ) . '.</code>';
2495  
2496          $result = array(
2497              'badge'       => array(
2498                  'label' => __( 'Performance' ),
2499                  'color' => 'blue',
2500              ),
2501              'description' => wp_kses_post( $description ),
2502              'test'        => 'page_cache',
2503              'status'      => 'good',
2504              'label'       => '',
2505              'actions'     => sprintf(
2506                  '<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>',
2507                  __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#Caching' ),
2508                  __( 'Learn more about page cache' ),
2509                  /* translators: Hidden accessibility text. */
2510                  __( '(opens in a new tab)' )
2511              ),
2512          );
2513  
2514          $page_cache_detail = $this->get_page_cache_detail();
2515  
2516          if ( is_wp_error( $page_cache_detail ) ) {
2517              $result['label']  = __( 'Unable to detect the presence of page cache' );
2518              $result['status'] = 'recommended';
2519              $error_info       = sprintf(
2520              /* translators: 1: Error message, 2: Error code. */
2521                  __( '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)' ),
2522                  $page_cache_detail->get_error_message(),
2523                  $page_cache_detail->get_error_code()
2524              );
2525              $result['description'] = wp_kses_post( "<p>$error_info</p>" ) . $result['description'];
2526              return $result;
2527          }
2528  
2529          $result['status'] = $page_cache_detail['status'];
2530  
2531          switch ( $page_cache_detail['status'] ) {
2532              case 'recommended':
2533                  $result['label'] = __( 'Page cache is not detected but the server response time is OK' );
2534                  break;
2535              case 'good':
2536                  $result['label'] = __( 'Page cache is detected and the server response time is good' );
2537                  break;
2538              default:
2539                  if ( empty( $page_cache_detail['headers'] ) && ! $page_cache_detail['advanced_cache_present'] ) {
2540                      $result['label'] = __( 'Page cache is not detected and the server response time is slow' );
2541                  } else {
2542                      $result['label'] = __( 'Page cache is detected but the server response time is still slow' );
2543                  }
2544          }
2545  
2546          $page_cache_test_summary = array();
2547  
2548          if ( empty( $page_cache_detail['response_time'] ) ) {
2549              $page_cache_test_summary[] = '<span class="dashicons dashicons-dismiss"></span> ' . __( 'Server response time could not be determined. Verify that loopback requests are working.' );
2550          } else {
2551  
2552              $threshold = $this->get_good_response_time_threshold();
2553              if ( $page_cache_detail['response_time'] < $threshold ) {
2554                  $page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt"></span> ' . sprintf(
2555                      /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
2556                      __( 'Median server response time was %1$s milliseconds. This is less than the recommended %2$s milliseconds threshold.' ),
2557                      number_format_i18n( $page_cache_detail['response_time'] ),
2558                      number_format_i18n( $threshold )
2559                  );
2560              } else {
2561                  $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . sprintf(
2562                      /* translators: 1: The response time in milliseconds, 2: The recommended threshold in milliseconds. */
2563                      __( 'Median server response time was %1$s milliseconds. It should be less than the recommended %2$s milliseconds threshold.' ),
2564                      number_format_i18n( $page_cache_detail['response_time'] ),
2565                      number_format_i18n( $threshold )
2566                  );
2567              }
2568  
2569              if ( empty( $page_cache_detail['headers'] ) ) {
2570                  $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . __( 'No client caching response headers were detected.' );
2571              } else {
2572                  $headers_summary  = '<span class="dashicons dashicons-yes-alt"></span>';
2573                  $headers_summary .= ' ' . sprintf(
2574                      /* translators: %d: Number of caching headers. */
2575                      _n(
2576                          'There was %d client caching response header detected:',
2577                          'There were %d client caching response headers detected:',
2578                          count( $page_cache_detail['headers'] )
2579                      ),
2580                      count( $page_cache_detail['headers'] )
2581                  );
2582                  $headers_summary          .= ' <code>' . implode( '</code>, <code>', $page_cache_detail['headers'] ) . '</code>.';
2583                  $page_cache_test_summary[] = $headers_summary;
2584              }
2585          }
2586  
2587          if ( $page_cache_detail['advanced_cache_present'] ) {
2588              $page_cache_test_summary[] = '<span class="dashicons dashicons-yes-alt"></span> ' . __( 'A page cache plugin was detected.' );
2589          } elseif ( ! ( is_array( $page_cache_detail ) && ! empty( $page_cache_detail['headers'] ) ) ) {
2590              // Note: This message is not shown if client caching response headers were present since an external caching layer may be employed.
2591              $page_cache_test_summary[] = '<span class="dashicons dashicons-warning"></span> ' . __( 'A page cache plugin was not detected.' );
2592          }
2593  
2594          $result['description'] .= '<ul><li>' . implode( '</li><li>', $page_cache_test_summary ) . '</li></ul>';
2595          return $result;
2596      }
2597  
2598      /**
2599       * Tests if the site uses persistent object cache and recommends to use it if not.
2600       *
2601       * @since 6.1.0
2602       *
2603       * @return array The test result.
2604       */
2605  	public function get_test_persistent_object_cache() {
2606          /**
2607           * Filters the action URL for the persistent object cache health check.
2608           *
2609           * @since 6.1.0
2610           *
2611           * @param string $action_url Learn more link for persistent object cache health check.
2612           */
2613          $action_url = apply_filters(
2614              'site_status_persistent_object_cache_url',
2615              /* translators: Localized Support reference. */
2616              __( 'https://developer.wordpress.org/advanced-administration/performance/optimization/#persistent-object-cache' )
2617          );
2618  
2619          $result = array(
2620              'test'        => 'persistent_object_cache',
2621              'status'      => 'good',
2622              'badge'       => array(
2623                  'label' => __( 'Performance' ),
2624                  'color' => 'blue',
2625              ),
2626              'label'       => __( 'A persistent object cache is being used' ),
2627              'description' => sprintf(
2628                  '<p>%s</p>',
2629                  __( '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.' )
2630              ),
2631              'actions'     => sprintf(
2632                  '<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>',
2633                  esc_url( $action_url ),
2634                  __( 'Learn more about persistent object caching.' ),
2635                  /* translators: Hidden accessibility text. */
2636                  __( '(opens in a new tab)' )
2637              ),
2638          );
2639  
2640          if ( wp_using_ext_object_cache() ) {
2641              return $result;
2642          }
2643  
2644          if ( ! $this->should_suggest_persistent_object_cache() ) {
2645              $result['label'] = __( 'A persistent object cache is not required' );
2646  
2647              return $result;
2648          }
2649  
2650          $available_services = $this->available_object_cache_services();
2651  
2652          $notes = __( 'Your hosting provider can tell you if a persistent object cache can be enabled on your site.' );
2653  
2654          if ( ! empty( $available_services ) ) {
2655              $notes .= ' ' . sprintf(
2656                  /* translators: Available object caching services. */
2657                  __( 'Your host appears to support the following object caching services: %s.' ),
2658                  implode( ', ', $available_services )
2659              );
2660          }
2661  
2662          /**
2663           * Filters the second paragraph of the health check's description
2664           * when suggesting the use of a persistent object cache.
2665           *
2666           * Hosts may want to replace the notes to recommend their preferred object caching solution.
2667           *
2668           * Plugin authors may want to append notes (not replace) on why object caching is recommended for their plugin.
2669           *
2670           * @since 6.1.0
2671           *
2672           * @param string   $notes              The notes appended to the health check description.
2673           * @param string[] $available_services The list of available persistent object cache services.
2674           */
2675          $notes = apply_filters( 'site_status_persistent_object_cache_notes', $notes, $available_services );
2676  
2677          $result['status']       = 'recommended';
2678          $result['label']        = __( 'You should use a persistent object cache' );
2679          $result['description'] .= sprintf(
2680              '<p>%s</p>',
2681              wp_kses(
2682                  $notes,
2683                  array(
2684                      'a'      => array( 'href' => true ),
2685                      'code'   => true,
2686                      'em'     => true,
2687                      'strong' => true,
2688                  )
2689              )
2690          );
2691  
2692          return $result;
2693      }
2694  
2695      /**
2696       * Returns a set of tests that belong to the site status page.
2697       *
2698       * Each site status test is defined here, they may be `direct` tests, that run on page load, or `async` tests
2699       * which will run later down the line via JavaScript calls to improve page performance and hopefully also user
2700       * experiences.
2701       *
2702       * @since 5.2.0
2703       * @since 5.6.0 Added support for `has_rest` and `permissions`.
2704       *
2705       * @return array The list of tests to run.
2706       */
2707  	public static function get_tests() {
2708          $tests = array(
2709              'direct' => array(
2710                  'wordpress_version'            => array(
2711                      'label' => __( 'WordPress Version' ),
2712                      'test'  => 'wordpress_version',
2713                  ),
2714                  'plugin_version'               => array(
2715                      'label' => __( 'Plugin Versions' ),
2716                      'test'  => 'plugin_version',
2717                  ),
2718                  'theme_version'                => array(
2719                      'label' => __( 'Theme Versions' ),
2720                      'test'  => 'theme_version',
2721                  ),
2722                  'php_version'                  => array(
2723                      'label' => __( 'PHP Version' ),
2724                      'test'  => 'php_version',
2725                  ),
2726                  'php_extensions'               => array(
2727                      'label' => __( 'PHP Extensions' ),
2728                      'test'  => 'php_extensions',
2729                  ),
2730                  'php_default_timezone'         => array(
2731                      'label' => __( 'PHP Default Timezone' ),
2732                      'test'  => 'php_default_timezone',
2733                  ),
2734                  'php_sessions'                 => array(
2735                      'label' => __( 'PHP Sessions' ),
2736                      'test'  => 'php_sessions',
2737                  ),
2738                  'sql_server'                   => array(
2739                      'label' => __( 'Database Server version' ),
2740                      'test'  => 'sql_server',
2741                  ),
2742                  'utf8mb4_support'              => array(
2743                      'label' => __( 'MySQL utf8mb4 support' ),
2744                      'test'  => 'utf8mb4_support',
2745                  ),
2746                  'ssl_support'                  => array(
2747                      'label' => __( 'Secure communication' ),
2748                      'test'  => 'ssl_support',
2749                  ),
2750                  'scheduled_events'             => array(
2751                      'label' => __( 'Scheduled events' ),
2752                      'test'  => 'scheduled_events',
2753                  ),
2754                  'http_requests'                => array(
2755                      'label' => __( 'HTTP Requests' ),
2756                      'test'  => 'http_requests',
2757                  ),
2758                  'rest_availability'            => array(
2759                      'label'     => __( 'REST API availability' ),
2760                      'test'      => 'rest_availability',
2761                      'skip_cron' => true,
2762                  ),
2763                  'debug_enabled'                => array(
2764                      'label' => __( 'Debugging enabled' ),
2765                      'test'  => 'is_in_debug_mode',
2766                  ),
2767                  'file_uploads'                 => array(
2768                      'label' => __( 'File uploads' ),
2769                      'test'  => 'file_uploads',
2770                  ),
2771                  'plugin_theme_auto_updates'    => array(
2772                      'label' => __( 'Plugin and theme auto-updates' ),
2773                      'test'  => 'plugin_theme_auto_updates',
2774                  ),
2775                  'update_temp_backup_writable'  => array(
2776                      'label' => __( 'Plugin and theme temporary backup directory access' ),
2777                      'test'  => 'update_temp_backup_writable',
2778                  ),
2779                  'available_updates_disk_space' => array(
2780                      'label' => __( 'Available disk space' ),
2781                      'test'  => 'available_updates_disk_space',
2782                  ),
2783              ),
2784              'async'  => array(
2785                  'dotorg_communication' => array(
2786                      'label'             => __( 'Communication with WordPress.org' ),
2787                      'test'              => rest_url( 'wp-site-health/v1/tests/dotorg-communication' ),
2788                      'has_rest'          => true,
2789                      'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_dotorg_communication' ),
2790                  ),
2791                  'background_updates'   => array(
2792                      'label'             => __( 'Background updates' ),
2793                      'test'              => rest_url( 'wp-site-health/v1/tests/background-updates' ),
2794                      'has_rest'          => true,
2795                      'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_background_updates' ),
2796                  ),
2797                  'loopback_requests'    => array(
2798                      'label'             => __( 'Loopback request' ),
2799                      'test'              => rest_url( 'wp-site-health/v1/tests/loopback-requests' ),
2800                      'has_rest'          => true,
2801                      'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_loopback_requests' ),
2802                  ),
2803                  'https_status'         => array(
2804                      'label'             => __( 'HTTPS status' ),
2805                      'test'              => rest_url( 'wp-site-health/v1/tests/https-status' ),
2806                      'has_rest'          => true,
2807                      'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_https_status' ),
2808                  ),
2809              ),
2810          );
2811  
2812          // Conditionally include Authorization header test if the site isn't protected by Basic Auth.
2813          if ( ! wp_is_site_protected_by_basic_auth() ) {
2814              $tests['async']['authorization_header'] = array(
2815                  'label'     => __( 'Authorization header' ),
2816                  'test'      => rest_url( 'wp-site-health/v1/tests/authorization-header' ),
2817                  'has_rest'  => true,
2818                  'headers'   => array( 'Authorization' => 'Basic ' . base64_encode( 'user:pwd' ) ),
2819                  'skip_cron' => true,
2820              );
2821          }
2822  
2823          // Only check for caches in production environments.
2824          if ( 'production' === wp_get_environment_type() ) {
2825              $tests['async']['page_cache'] = array(
2826                  'label'             => __( 'Page cache' ),
2827                  'test'              => rest_url( 'wp-site-health/v1/tests/page-cache' ),
2828                  'has_rest'          => true,
2829                  'async_direct_test' => array( WP_Site_Health::get_instance(), 'get_test_page_cache' ),
2830              );
2831  
2832              $tests['direct']['persistent_object_cache'] = array(
2833                  'label' => __( 'Persistent object cache' ),
2834                  'test'  => 'persistent_object_cache',
2835              );
2836          }
2837  
2838          /**
2839           * Filters which site status tests are run on a site.
2840           *
2841           * The site health is determined by a set of tests based on best practices from
2842           * both the WordPress Hosting Team and web standards in general.
2843           *
2844           * Some sites may not have the same requirements, for example the automatic update
2845           * checks may be handled by a host, and are therefore disabled in core.
2846           * Or maybe you want to introduce a new test, is caching enabled/disabled/stale for example.
2847           *
2848           * Tests may be added either as direct, or asynchronous ones. Any test that may require some time
2849           * to complete should run asynchronously, to avoid extended loading periods within wp-admin.
2850           *
2851           * @since 5.2.0
2852           * @since 5.6.0 Added the `async_direct_test` array key for asynchronous tests.
2853           *              Added the `skip_cron` array key for all tests.
2854           *
2855           * @param array[] $tests {
2856           *     An associative array of direct and asynchronous tests.
2857           *
2858           *     @type array[] $direct {
2859           *         An array of direct tests.
2860           *
2861           *         @type array ...$identifier {
2862           *             `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
2863           *             prefix test identifiers with their slug to avoid collisions between tests.
2864           *
2865           *             @type string   $label     The friendly label to identify the test.
2866           *             @type callable $test      The callback function that runs the test and returns its result.
2867           *             @type bool     $skip_cron Whether to skip this test when running as cron.
2868           *         }
2869           *     }
2870           *     @type array[] $async {
2871           *         An array of asynchronous tests.
2872           *
2873           *         @type array ...$identifier {
2874           *             `$identifier` should be a unique identifier for the test. Plugins and themes are encouraged to
2875           *             prefix test identifiers with their slug to avoid collisions between tests.
2876           *
2877           *             @type string   $label             The friendly label to identify the test.
2878           *             @type string   $test              An admin-ajax.php action to be called to perform the test, or
2879           *                                               if `$has_rest` is true, a URL to a REST API endpoint to perform
2880           *                                               the test.
2881           *             @type bool     $has_rest          Whether the `$test` property points to a REST API endpoint.
2882           *             @type bool     $skip_cron         Whether to skip this test when running as cron.
2883           *             @type callable $async_direct_test A manner of directly calling the test marked as asynchronous,
2884           *                                               as the scheduled event can not authenticate, and endpoints
2885           *                                               may require authentication.
2886           *         }
2887           *     }
2888           * }
2889           */
2890          $tests = apply_filters( 'site_status_tests', $tests );
2891  
2892          // Ensure that the filtered tests contain the required array keys.
2893          $tests = array_merge(
2894              array(
2895                  'direct' => array(),
2896                  'async'  => array(),
2897              ),
2898              $tests
2899          );
2900  
2901          return $tests;
2902      }
2903  
2904      /**
2905       * Adds a class to the body HTML tag.
2906       *
2907       * Filters the body class string for admin pages and adds our own class for easier styling.
2908       *
2909       * @since 5.2.0
2910       *
2911       * @param string $body_class The body class string.
2912       * @return string The modified body class string.
2913       */
2914  	public function admin_body_class( $body_class ) {
2915          $screen = get_current_screen();
2916          if ( 'site-health' !== $screen->id ) {
2917              return $body_class;
2918          }
2919  
2920          $body_class .= ' site-health';
2921  
2922          return $body_class;
2923      }
2924  
2925      /**
2926       * Initiates the WP_Cron schedule test cases.
2927       *
2928       * @since 5.2.0
2929       */
2930  	private function wp_schedule_test_init() {
2931          $this->schedules = wp_get_schedules();
2932          $this->get_cron_tasks();
2933      }
2934  
2935      /**
2936       * Populates the list of cron events and store them to a class-wide variable.
2937       *
2938       * @since 5.2.0
2939       */
2940  	private function get_cron_tasks() {
2941          $cron_tasks = _get_cron_array();
2942  
2943          if ( empty( $cron_tasks ) ) {
2944              $this->crons = new WP_Error( 'no_tasks', __( 'No scheduled events exist on this site.' ) );
2945              return;
2946          }
2947  
2948          $this->crons = array();
2949  
2950          foreach ( $cron_tasks as $time => $cron ) {
2951              foreach ( $cron as $hook => $dings ) {
2952                  foreach ( $dings as $sig => $data ) {
2953  
2954                      $this->crons[ "$hook-$sig-$time" ] = (object) array(
2955                          'hook'     => $hook,
2956                          'time'     => $time,
2957                          'sig'      => $sig,
2958                          'args'     => $data['args'],
2959                          'schedule' => $data['schedule'],
2960                          'interval' => isset( $data['interval'] ) ? $data['interval'] : null,
2961                      );
2962  
2963                  }
2964              }
2965          }
2966      }
2967  
2968      /**
2969       * Checks if any scheduled tasks have been missed.
2970       *
2971       * Returns a boolean value of `true` if a scheduled task has been missed and ends processing.
2972       *
2973       * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value.
2974       *
2975       * @since 5.2.0
2976       *
2977       * @return bool|WP_Error True if a cron was missed, false if not. WP_Error if the cron is set to that.
2978       */
2979  	public function has_missed_cron() {
2980          if ( is_wp_error( $this->crons ) ) {
2981              return $this->crons;
2982          }
2983  
2984          foreach ( $this->crons as $id => $cron ) {
2985              if ( ( $cron->time - time() ) < $this->timeout_missed_cron ) {
2986                  $this->last_missed_cron = $cron->hook;
2987                  return true;
2988              }
2989          }
2990  
2991          return false;
2992      }
2993  
2994      /**
2995       * Checks if any scheduled tasks are late.
2996       *
2997       * Returns a boolean value of `true` if a scheduled task is late and ends processing.
2998       *
2999       * If the list of crons is an instance of WP_Error, returns the instance instead of a boolean value.
3000       *
3001       * @since 5.3.0
3002       *
3003       * @return bool|WP_Error True if a cron is late, false if not. WP_Error if the cron is set to that.
3004       */
3005  	public function has_late_cron() {
3006          if ( is_wp_error( $this->crons ) ) {
3007              return $this->crons;
3008          }
3009  
3010          foreach ( $this->crons as $id => $cron ) {
3011              $cron_offset = $cron->time - time();
3012              if (
3013                  $cron_offset >= $this->timeout_missed_cron &&
3014                  $cron_offset < $this->timeout_late_cron
3015              ) {
3016                  $this->last_late_cron = $cron->hook;
3017                  return true;
3018              }
3019          }
3020  
3021          return false;
3022      }
3023  
3024      /**
3025       * Checks for potential issues with plugin and theme auto-updates.
3026       *
3027       * Though there is no way to 100% determine if plugin and theme auto-updates are configured
3028       * correctly, a few educated guesses could be made to flag any conditions that would
3029       * potentially cause unexpected behaviors.
3030       *
3031       * @since 5.5.0
3032       *
3033       * @return object The test results.
3034       */
3035  	public function detect_plugin_theme_auto_update_issues() {
3036          $mock_plugin = (object) array(
3037              'id'            => 'w.org/plugins/a-fake-plugin',
3038              'slug'          => 'a-fake-plugin',
3039              'plugin'        => 'a-fake-plugin/a-fake-plugin.php',
3040              'new_version'   => '9.9',
3041              'url'           => 'https://wordpress.org/plugins/a-fake-plugin/',
3042              'package'       => 'https://downloads.wordpress.org/plugin/a-fake-plugin.9.9.zip',
3043              'icons'         => array(
3044                  '2x' => 'https://ps.w.org/a-fake-plugin/assets/icon-256x256.png',
3045                  '1x' => 'https://ps.w.org/a-fake-plugin/assets/icon-128x128.png',
3046              ),
3047              'banners'       => array(
3048                  '2x' => 'https://ps.w.org/a-fake-plugin/assets/banner-1544x500.png',
3049                  '1x' => 'https://ps.w.org/a-fake-plugin/assets/banner-772x250.png',
3050              ),
3051              'banners_rtl'   => array(),
3052              'tested'        => '5.5.0',
3053              'requires_php'  => '5.6.20',
3054              'compatibility' => new stdClass(),
3055          );
3056  
3057          $mock_theme = (object) array(
3058              'theme'        => 'a-fake-theme',
3059              'new_version'  => '9.9',
3060              'url'          => 'https://wordpress.org/themes/a-fake-theme/',
3061              'package'      => 'https://downloads.wordpress.org/theme/a-fake-theme.9.9.zip',
3062              'requires'     => '5.0.0',
3063              'requires_php' => '5.6.20',
3064          );
3065  
3066          $test_plugins_enabled = wp_is_auto_update_forced_for_item( 'plugin', true, $mock_plugin );
3067          $test_themes_enabled  = wp_is_auto_update_forced_for_item( 'theme', true, $mock_theme );
3068  
3069          $ui_enabled_for_plugins = wp_is_auto_update_enabled_for_type( 'plugin' );
3070          $ui_enabled_for_themes  = wp_is_auto_update_enabled_for_type( 'theme' );
3071          $plugin_filter_present  = has_filter( 'auto_update_plugin' );
3072          $theme_filter_present   = has_filter( 'auto_update_theme' );
3073  
3074          if ( ( ! $test_plugins_enabled && $ui_enabled_for_plugins )
3075              || ( ! $test_themes_enabled && $ui_enabled_for_themes )
3076          ) {
3077              return (object) array(
3078                  'status'  => 'critical',
3079                  '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.' ),
3080              );
3081          }
3082  
3083          if ( ( ! $test_plugins_enabled && $plugin_filter_present )
3084              && ( ! $test_themes_enabled && $theme_filter_present )
3085          ) {
3086              return (object) array(
3087                  'status'  => 'recommended',
3088                  'message' => __( 'Auto-updates for plugins and themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
3089              );
3090          } elseif ( ! $test_plugins_enabled && $plugin_filter_present ) {
3091              return (object) array(
3092                  'status'  => 'recommended',
3093                  'message' => __( 'Auto-updates for plugins appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
3094              );
3095          } elseif ( ! $test_themes_enabled && $theme_filter_present ) {
3096              return (object) array(
3097                  'status'  => 'recommended',
3098                  'message' => __( 'Auto-updates for themes appear to be disabled. This will prevent your site from receiving new versions automatically when available.' ),
3099              );
3100          }
3101  
3102          return (object) array(
3103              'status'  => 'good',
3104              'message' => __( 'There appear to be no issues with plugin and theme auto-updates.' ),
3105          );
3106      }
3107  
3108      /**
3109       * Runs a loopback test on the site.
3110       *
3111       * Loopbacks are what WordPress uses to communicate with itself to start up WP_Cron, scheduled posts,
3112       * make sure plugin or theme edits don't cause site failures and similar.
3113       *
3114       * @since 5.2.0
3115       *
3116       * @return object The test results.
3117       */
3118  	public function can_perform_loopback() {
3119          $body    = array( 'site-health' => 'loopback-test' );
3120          $cookies = wp_unslash( $_COOKIE );
3121          $timeout = 10; // 10 seconds.
3122          $headers = array(
3123              'Cache-Control' => 'no-cache',
3124          );
3125          /** This filter is documented in wp-includes/class-wp-http-streams.php */
3126          $sslverify = apply_filters( 'https_local_ssl_verify', false );
3127  
3128          // Include Basic auth in loopback requests.
3129          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
3130              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
3131          }
3132  
3133          $url = site_url( 'wp-cron.php' );
3134  
3135          /*
3136           * A post request is used for the wp-cron.php loopback test to cause the file
3137           * to finish early without triggering cron jobs. This has two benefits:
3138           * - cron jobs are not triggered a second time on the site health page,
3139           * - the loopback request finishes sooner providing a quicker result.
3140           *
3141           * Using a POST request causes the loopback to differ slightly to the standard
3142           * GET request WordPress uses for wp-cron.php loopback requests but is close
3143           * enough. See https://core.trac.wordpress.org/ticket/52547
3144           */
3145          $r = wp_remote_post( $url, compact( 'body', 'cookies', 'headers', 'timeout', 'sslverify' ) );
3146  
3147          if ( is_wp_error( $r ) ) {
3148              return (object) array(
3149                  'status'  => 'critical',
3150                  'message' => sprintf(
3151                      '%s<br>%s',
3152                      __( 'The loopback request to your site failed, this means features relying on them are not currently working as expected.' ),
3153                      sprintf(
3154                          /* translators: 1: The WordPress error message. 2: The WordPress error code. */
3155                          __( 'Error: %1$s (%2$s)' ),
3156                          $r->get_error_message(),
3157                          $r->get_error_code()
3158                      )
3159                  ),
3160              );
3161          }
3162  
3163          if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
3164              return (object) array(
3165                  'status'  => 'recommended',
3166                  'message' => sprintf(
3167                      /* translators: %d: The HTTP response code returned. */
3168                      __( '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.' ),
3169                      wp_remote_retrieve_response_code( $r )
3170                  ),
3171              );
3172          }
3173  
3174          return (object) array(
3175              'status'  => 'good',
3176              'message' => __( 'The loopback request to your site completed successfully.' ),
3177          );
3178      }
3179  
3180      /**
3181       * Creates a weekly cron event, if one does not already exist.
3182       *
3183       * @since 5.4.0
3184       */
3185  	public function maybe_create_scheduled_event() {
3186          if ( ! wp_next_scheduled( 'wp_site_health_scheduled_check' ) && ! wp_installing() ) {
3187              wp_schedule_event( time() + DAY_IN_SECONDS, 'weekly', 'wp_site_health_scheduled_check' );
3188          }
3189      }
3190  
3191      /**
3192       * Runs the scheduled event to check and update the latest site health status for the website.
3193       *
3194       * @since 5.4.0
3195       */
3196  	public function wp_cron_scheduled_check() {
3197          // Bootstrap wp-admin, as WP_Cron doesn't do this for us.
3198          require_once trailingslashit( ABSPATH ) . 'wp-admin/includes/admin.php';
3199  
3200          $tests = WP_Site_Health::get_tests();
3201  
3202          $results = array();
3203  
3204          $site_status = array(
3205              'good'        => 0,
3206              'recommended' => 0,
3207              'critical'    => 0,
3208          );
3209  
3210          // Don't run https test on development environments.
3211          if ( $this->is_development_environment() ) {
3212              unset( $tests['async']['https_status'] );
3213          }
3214  
3215          foreach ( $tests['direct'] as $test ) {
3216              if ( ! empty( $test['skip_cron'] ) ) {
3217                  continue;
3218              }
3219  
3220              if ( is_string( $test['test'] ) ) {
3221                  $test_function = sprintf(
3222                      'get_test_%s',
3223                      $test['test']
3224                  );
3225  
3226                  if ( method_exists( $this, $test_function ) && is_callable( array( $this, $test_function ) ) ) {
3227                      $results[] = $this->perform_test( array( $this, $test_function ) );
3228                      continue;
3229                  }
3230              }
3231  
3232              if ( is_callable( $test['test'] ) ) {
3233                  $results[] = $this->perform_test( $test['test'] );
3234              }
3235          }
3236  
3237          foreach ( $tests['async'] as $test ) {
3238              if ( ! empty( $test['skip_cron'] ) ) {
3239                  continue;
3240              }
3241  
3242              // Local endpoints may require authentication, so asynchronous tests can pass a direct test runner as well.
3243              if ( ! empty( $test['async_direct_test'] ) && is_callable( $test['async_direct_test'] ) ) {
3244                  // This test is callable, do so and continue to the next asynchronous check.
3245                  $results[] = $this->perform_test( $test['async_direct_test'] );
3246                  continue;
3247              }
3248  
3249              if ( is_string( $test['test'] ) ) {
3250                  // Check if this test has a REST API endpoint.
3251                  if ( isset( $test['has_rest'] ) && $test['has_rest'] ) {
3252                      $result_fetch = wp_remote_get(
3253                          $test['test'],
3254                          array(
3255                              'body' => array(
3256                                  '_wpnonce' => wp_create_nonce( 'wp_rest' ),
3257                              ),
3258                          )
3259                      );
3260                  } else {
3261                      $result_fetch = wp_remote_post(
3262                          admin_url( 'admin-ajax.php' ),
3263                          array(
3264                              'body' => array(
3265                                  'action'   => $test['test'],
3266                                  '_wpnonce' => wp_create_nonce( 'health-check-site-status' ),
3267                              ),
3268                          )
3269                      );
3270                  }
3271  
3272                  if ( ! is_wp_error( $result_fetch ) && 200 === wp_remote_retrieve_response_code( $result_fetch ) ) {
3273                      $result = json_decode( wp_remote_retrieve_body( $result_fetch ), true );
3274                  } else {
3275                      $result = false;
3276                  }
3277  
3278                  if ( is_array( $result ) ) {
3279                      $results[] = $result;
3280                  } else {
3281                      $results[] = array(
3282                          'status' => 'recommended',
3283                          'label'  => __( 'A test is unavailable' ),
3284                      );
3285                  }
3286              }
3287          }
3288  
3289          foreach ( $results as $result ) {
3290              if ( 'critical' === $result['status'] ) {
3291                  ++$site_status['critical'];
3292              } elseif ( 'recommended' === $result['status'] ) {
3293                  ++$site_status['recommended'];
3294              } else {
3295                  ++$site_status['good'];
3296              }
3297          }
3298  
3299          set_transient( 'health-check-site-status-result', wp_json_encode( $site_status ) );
3300      }
3301  
3302      /**
3303       * Checks if the current environment type is set to 'development' or 'local'.
3304       *
3305       * @since 5.6.0
3306       *
3307       * @return bool True if it is a development environment, false if not.
3308       */
3309  	public function is_development_environment() {
3310          return in_array( wp_get_environment_type(), array( 'development', 'local' ), true );
3311      }
3312  
3313      /**
3314       * Returns a list of headers and its verification callback to verify if page cache is enabled or not.
3315       *
3316       * Note: key is header name and value could be callable function to verify header value.
3317       * Empty value mean existence of header detect page cache is enabled.
3318       *
3319       * @since 6.1.0
3320       *
3321       * @return array List of client caching headers and their (optional) verification callbacks.
3322       */
3323  	public function get_page_cache_headers() {
3324  
3325          $cache_hit_callback = static function ( $header_value ) {
3326              return str_contains( strtolower( $header_value ), 'hit' );
3327          };
3328  
3329          $cache_headers = array(
3330              'cache-control'          => static function ( $header_value ) {
3331                  return (bool) preg_match( '/max-age=[1-9]/', $header_value );
3332              },
3333              'expires'                => static function ( $header_value ) {
3334                  return strtotime( $header_value ) > time();
3335              },
3336              'age'                    => static function ( $header_value ) {
3337                  return is_numeric( $header_value ) && $header_value > 0;
3338              },
3339              'last-modified'          => '',
3340              'etag'                   => '',
3341              'x-cache-enabled'        => static function ( $header_value ) {
3342                  return 'true' === strtolower( $header_value );
3343              },
3344              'x-cache-disabled'       => static function ( $header_value ) {
3345                  return ( 'on' !== strtolower( $header_value ) );
3346              },
3347              'x-srcache-store-status' => $cache_hit_callback,
3348              'x-srcache-fetch-status' => $cache_hit_callback,
3349          );
3350  
3351          /**
3352           * Filters the list of cache headers supported by core.
3353           *
3354           * @since 6.1.0
3355           *
3356           * @param array $cache_headers Array of supported cache headers.
3357           */
3358          return apply_filters( 'site_status_page_cache_supported_cache_headers', $cache_headers );
3359      }
3360  
3361      /**
3362       * Checks if site has page cache enabled or not.
3363       *
3364       * @since 6.1.0
3365       *
3366       * @return WP_Error|array {
3367       *     Page cache detection details or else error information.
3368       *
3369       *     @type bool    $advanced_cache_present        Whether a page cache plugin is present.
3370       *     @type array[] $page_caching_response_headers Sets of client caching headers for the responses.
3371       *     @type float[] $response_timing               Response timings.
3372       * }
3373       */
3374  	private function check_for_page_caching() {
3375  
3376          /** This filter is documented in wp-includes/class-wp-http-streams.php */
3377          $sslverify = apply_filters( 'https_local_ssl_verify', false );
3378  
3379          $headers = array();
3380  
3381          /*
3382           * Include basic auth in loopback requests. Note that this will only pass along basic auth when user is
3383           * initiating the test. If a site requires basic auth, the test will fail when it runs in WP Cron as part of
3384           * wp_site_health_scheduled_check. This logic is copied from WP_Site_Health::can_perform_loopback().
3385           */
3386          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
3387              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
3388          }
3389  
3390          $caching_headers               = $this->get_page_cache_headers();
3391          $page_caching_response_headers = array();
3392          $response_timing               = array();
3393  
3394          for ( $i = 1; $i <= 3; $i++ ) {
3395              $start_time    = microtime( true );
3396              $http_response = wp_remote_get( home_url( '/' ), compact( 'sslverify', 'headers' ) );
3397              $end_time      = microtime( true );
3398  
3399              if ( is_wp_error( $http_response ) ) {
3400                  return $http_response;
3401              }
3402              if ( wp_remote_retrieve_response_code( $http_response ) !== 200 ) {
3403                  return new WP_Error(
3404                      'http_' . wp_remote_retrieve_response_code( $http_response ),
3405                      wp_remote_retrieve_response_message( $http_response )
3406                  );
3407              }
3408  
3409              $response_headers = array();
3410  
3411              foreach ( $caching_headers as $header => $callback ) {
3412                  $header_values = wp_remote_retrieve_header( $http_response, $header );
3413                  if ( empty( $header_values ) ) {
3414                      continue;
3415                  }
3416                  $header_values = (array) $header_values;
3417                  if ( empty( $callback ) || ( is_callable( $callback ) && count( array_filter( $header_values, $callback ) ) > 0 ) ) {
3418                      $response_headers[ $header ] = $header_values;
3419                  }
3420              }
3421  
3422              $page_caching_response_headers[] = $response_headers;
3423              $response_timing[]               = ( $end_time - $start_time ) * 1000;
3424          }
3425  
3426          return array(
3427              'advanced_cache_present'        => (
3428                  file_exists( WP_CONTENT_DIR . '/advanced-cache.php' )
3429                  &&
3430                  ( defined( 'WP_CACHE' ) && WP_CACHE )
3431                  &&
3432                  /** This filter is documented in wp-settings.php */
3433                  apply_filters( 'enable_loading_advanced_cache_dropin', true )
3434              ),
3435              'page_caching_response_headers' => $page_caching_response_headers,
3436              'response_timing'               => $response_timing,
3437          );
3438      }
3439  
3440      /**
3441       * Gets page cache details.
3442       *
3443       * @since 6.1.0
3444       *
3445       * @return WP_Error|array {
3446       *    Page cache detail or else a WP_Error if unable to determine.
3447       *
3448       *    @type string   $status                 Page cache status. Good, Recommended or Critical.
3449       *    @type bool     $advanced_cache_present Whether page cache plugin is available or not.
3450       *    @type string[] $headers                Client caching response headers detected.
3451       *    @type float    $response_time          Response time of site.
3452       * }
3453       */
3454  	private function get_page_cache_detail() {
3455          $page_cache_detail = $this->check_for_page_caching();
3456          if ( is_wp_error( $page_cache_detail ) ) {
3457              return $page_cache_detail;
3458          }
3459  
3460          // Use the median server response time.
3461          $response_timings = $page_cache_detail['response_timing'];
3462          rsort( $response_timings );
3463          $page_speed = $response_timings[ floor( count( $response_timings ) / 2 ) ];
3464  
3465          // Obtain unique set of all client caching response headers.
3466          $headers = array();
3467          foreach ( $page_cache_detail['page_caching_response_headers'] as $page_caching_response_headers ) {
3468              $headers = array_merge( $headers, array_keys( $page_caching_response_headers ) );
3469          }
3470          $headers = array_unique( $headers );
3471  
3472          // Page cache is detected if there are response headers or a page cache plugin is present.
3473          $has_page_caching = ( count( $headers ) > 0 || $page_cache_detail['advanced_cache_present'] );
3474  
3475          if ( $page_speed && $page_speed < $this->get_good_response_time_threshold() ) {
3476              $result = $has_page_caching ? 'good' : 'recommended';
3477          } else {
3478              $result = 'critical';
3479          }
3480  
3481          return array(
3482              'status'                 => $result,
3483              'advanced_cache_present' => $page_cache_detail['advanced_cache_present'],
3484              'headers'                => $headers,
3485              'response_time'          => $page_speed,
3486          );
3487      }
3488  
3489      /**
3490       * Gets the threshold below which a response time is considered good.
3491       *
3492       * @since 6.1.0
3493       *
3494       * @return int Threshold in milliseconds.
3495       */
3496  	private function get_good_response_time_threshold() {
3497          /**
3498           * Filters the threshold below which a response time is considered good.
3499           *
3500           * The default is based on https://web.dev/time-to-first-byte/.
3501           *
3502           * @param int $threshold Threshold in milliseconds. Default 600.
3503           *
3504           * @since 6.1.0
3505           */
3506          return (int) apply_filters( 'site_status_good_response_time_threshold', 600 );
3507      }
3508  
3509      /**
3510       * Determines whether to suggest using a persistent object cache.
3511       *
3512       * @since 6.1.0
3513       *
3514       * @global wpdb $wpdb WordPress database abstraction object.
3515       *
3516       * @return bool Whether to suggest using a persistent object cache.
3517       */
3518  	public function should_suggest_persistent_object_cache() {
3519          global $wpdb;
3520  
3521          /**
3522           * Filters whether to suggest use of a persistent object cache and bypass default threshold checks.
3523           *
3524           * Using this filter allows to override the default logic, effectively short-circuiting the method.
3525           *
3526           * @since 6.1.0
3527           *
3528           * @param bool|null $suggest Boolean to short-circuit, for whether to suggest using a persistent object cache.
3529           *                           Default null.
3530           */
3531          $short_circuit = apply_filters( 'site_status_should_suggest_persistent_object_cache', null );
3532          if ( is_bool( $short_circuit ) ) {
3533              return $short_circuit;
3534          }
3535  
3536          if ( is_multisite() ) {
3537              return true;
3538          }
3539  
3540          /**
3541           * Filters the thresholds used to determine whether to suggest the use of a persistent object cache.
3542           *
3543           * @since 6.1.0
3544           *
3545           * @param int[] $thresholds The list of threshold numbers keyed by threshold name.
3546           */
3547          $thresholds = apply_filters(
3548              'site_status_persistent_object_cache_thresholds',
3549              array(
3550                  'alloptions_count' => 500,
3551                  'alloptions_bytes' => 100000,
3552                  'comments_count'   => 1000,
3553                  'options_count'    => 1000,
3554                  'posts_count'      => 1000,
3555                  'terms_count'      => 1000,
3556                  'users_count'      => 1000,
3557              )
3558          );
3559  
3560          $alloptions = wp_load_alloptions();
3561  
3562          if ( $thresholds['alloptions_count'] < count( $alloptions ) ) {
3563              return true;
3564          }
3565  
3566          if ( $thresholds['alloptions_bytes'] < strlen( serialize( $alloptions ) ) ) {
3567              return true;
3568          }
3569  
3570          $table_names = implode( "','", array( $wpdb->comments, $wpdb->options, $wpdb->posts, $wpdb->terms, $wpdb->users ) );
3571  
3572          // With InnoDB the `TABLE_ROWS` are estimates, which are accurate enough and faster to retrieve than individual `COUNT()` queries.
3573          $results = $wpdb->get_results(
3574              $wpdb->prepare(
3575                  // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- This query cannot use interpolation.
3576                  "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;",
3577                  DB_NAME
3578              ),
3579              OBJECT_K
3580          );
3581  
3582          $threshold_map = array(
3583              'comments_count' => $wpdb->comments,
3584              'options_count'  => $wpdb->options,
3585              'posts_count'    => $wpdb->posts,
3586              'terms_count'    => $wpdb->terms,
3587              'users_count'    => $wpdb->users,
3588          );
3589  
3590          foreach ( $threshold_map as $threshold => $table ) {
3591              if ( $thresholds[ $threshold ] <= $results[ $table ]->rows ) {
3592                  return true;
3593              }
3594          }
3595  
3596          return false;
3597      }
3598  
3599      /**
3600       * Returns a list of available persistent object cache services.
3601       *
3602       * @since 6.1.0
3603       *
3604       * @return string[] The list of available persistent object cache services.
3605       */
3606  	private function available_object_cache_services() {
3607          $extensions = array_map(
3608              'extension_loaded',
3609              array(
3610                  'APCu'      => 'apcu',
3611                  'Redis'     => 'redis',
3612                  'Relay'     => 'relay',
3613                  'Memcache'  => 'memcache',
3614                  'Memcached' => 'memcached',
3615              )
3616          );
3617  
3618          $services = array_keys( array_filter( $extensions ) );
3619  
3620          /**
3621           * Filters the persistent object cache services available to the user.
3622           *
3623           * This can be useful to hide or add services not included in the defaults.
3624           *
3625           * @since 6.1.0
3626           *
3627           * @param string[] $services The list of available persistent object cache services.
3628           */
3629          return apply_filters( 'site_status_available_object_cache_services', $services );
3630      }
3631  }


Generated : Mon Mar 18 08:20:01 2024 Cross-referenced by PHPXref