[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-admin/includes/ -> class-wp-automatic-updater.php (source)

   1  <?php
   2  /**
   3   * Upgrade API: WP_Automatic_Updater class
   4   *
   5   * @package WordPress
   6   * @subpackage Upgrader
   7   * @since 4.6.0
   8   */
   9  
  10  /**
  11   * Core class used for handling automatic background updates.
  12   *
  13   * @since 3.7.0
  14   * @since 4.6.0 Moved to its own file from wp-admin/includes/class-wp-upgrader.php.
  15   *
  16   * @phpstan-type Core_Update_Offer object{
  17   *     current: string,
  18   *     version: string,
  19   *     php_version: string,
  20   *     mysql_version: string,
  21   *     new_files?: bool|string,
  22   *     notify_email?: bool|string,
  23   *     autoupdate?: bool,
  24   *     disable_autoupdate?: bool,
  25   * }&stdClass
  26   * @phpstan-type Plugin_Update_Offer object{
  27   *     slug: string,
  28   *     plugin: string,
  29   *     new_version: string,
  30   *     current_version?: string|false,
  31   *     requires_php?: string|false|null,
  32   *     autoupdate?: bool,
  33   *     disable_autoupdate?: bool,
  34   * }&stdClass
  35   * @phpstan-type Theme_Update_Offer object{
  36   *     theme: string,
  37   *     new_version: string,
  38   *     current_version?: string|false,
  39   *     requires_php?: string|false|null,
  40   *     autoupdate?: bool,
  41   *     disable_autoupdate?: bool,
  42   * }&stdClass
  43   * @phpstan-type Translation_Update_Offer object{
  44   *     language: string,
  45   *     autoupdate?: bool,
  46   *     disable_autoupdate?: bool,
  47   * }&stdClass
  48   * @phpstan-type Core_Update_Result object{
  49   *     item: Core_Update_Offer,
  50   *     result: string|WP_Error,
  51   *     name: string,
  52   *     messages: string[],
  53   * }&stdClass
  54   * @phpstan-type Plugin_Update_Result object{
  55   *     item: Plugin_Update_Offer,
  56   *     result: true|WP_Error|null,
  57   *     name: string,
  58   *     messages: string[],
  59   * }&stdClass
  60   * @phpstan-type Theme_Update_Result object{
  61   *     item: Theme_Update_Offer,
  62   *     result: true|WP_Error|null,
  63   *     name: string|false,
  64   *     messages: string[],
  65   * }&stdClass
  66   * @phpstan-type Translation_Update_Result object{
  67   *     item: Translation_Update_Offer,
  68   *     result: array<mixed>|true|WP_Error|null,
  69   *     name: string,
  70   *     messages: string[],
  71   * }&stdClass
  72   */
  73  #[AllowDynamicProperties]
  74  class WP_Automatic_Updater {
  75  
  76      /**
  77       * Tracks update results during processing.
  78       *
  79       * @var array<string, object[]>
  80       * @phpstan-var array{
  81       *     core?: list<Core_Update_Result>,
  82       *     plugin?: list<Plugin_Update_Result>,
  83       *     theme?: list<Theme_Update_Result>,
  84       *     translation?: list<Translation_Update_Result>,
  85       * }
  86       */
  87      protected $update_results = array();
  88  
  89      /**
  90       * Details of the fatal error detected by the last call to has_fatal_error().
  91       *
  92       * This is the fatal error, or the reason the loopback request to check for one failed.
  93       * It is null when no fatal error was detected.
  94       *
  95       * @since 7.2.0
  96       */
  97      private ?string $fatal_error_message = null;
  98  
  99      /**
 100       * Determines whether the entire automatic updater is disabled.
 101       *
 102       * @since 3.7.0
 103       *
 104       * @return bool True if the automatic updater is disabled, false otherwise.
 105       */
 106  	public function is_disabled() {
 107          // Background updates are disabled if you don't want file changes.
 108          if ( ! wp_is_file_mod_allowed( 'automatic_updater' ) ) {
 109              return true;
 110          }
 111  
 112          if ( wp_installing() ) {
 113              return true;
 114          }
 115  
 116          // More fine grained control can be done through the WP_AUTO_UPDATE_CORE constant and filters.
 117          $disabled = defined( 'AUTOMATIC_UPDATER_DISABLED' ) && AUTOMATIC_UPDATER_DISABLED;
 118  
 119          /**
 120           * Filters whether to entirely disable background updates.
 121           *
 122           * There are more fine-grained filters and controls for selective disabling.
 123           * This filter parallels the AUTOMATIC_UPDATER_DISABLED constant in name.
 124           *
 125           * This also disables update notification emails. That may change in the future.
 126           *
 127           * @since 3.7.0
 128           *
 129           * @param bool $disabled Whether the updater should be disabled.
 130           */
 131          return apply_filters( 'automatic_updater_disabled', $disabled );
 132      }
 133  
 134      /**
 135       * Checks whether access to a given directory is allowed.
 136       *
 137       * This is used when detecting version control checkouts. Takes into account
 138       * the PHP `open_basedir` restrictions, so that WordPress does not try to access
 139       * directories it is not allowed to.
 140       *
 141       * @since 6.2.0
 142       *
 143       * @param string $dir The directory to check.
 144       * @return bool True if access to the directory is allowed, false otherwise.
 145       */
 146  	public function is_allowed_dir( $dir ) {
 147          if ( is_string( $dir ) ) {
 148              $dir = trim( $dir );
 149          }
 150  
 151          if ( ! is_string( $dir ) || '' === $dir ) {
 152              _doing_it_wrong(
 153                  __METHOD__,
 154                  sprintf(
 155                      /* translators: %s: The "$dir" argument. */
 156                      __( 'The "%s" argument must be a non-empty string.' ),
 157                      '$dir'
 158                  ),
 159                  '6.2.0'
 160              );
 161  
 162              return false;
 163          }
 164  
 165          $open_basedir = ini_get( 'open_basedir' );
 166  
 167          if ( empty( $open_basedir ) ) {
 168              return true;
 169          }
 170  
 171          $open_basedir_list = explode( PATH_SEPARATOR, $open_basedir );
 172  
 173          foreach ( $open_basedir_list as $basedir ) {
 174              if ( '' !== trim( $basedir ) && str_starts_with( $dir, $basedir ) ) {
 175                  return true;
 176              }
 177          }
 178  
 179          return false;
 180      }
 181  
 182      /**
 183       * Checks for version control checkouts.
 184       *
 185       * Checks for Subversion, Git, Mercurial, and Bazaar. It recursively looks up the
 186       * filesystem to the top of the drive, erring on the side of detecting a VCS
 187       * checkout somewhere.
 188       *
 189       * ABSPATH is always checked in addition to whatever `$context` is (which may be the
 190       * wp-content directory, for example). The underlying assumption is that if you are
 191       * using version control *anywhere*, then you should be making decisions for
 192       * how things get updated.
 193       *
 194       * @since 3.7.0
 195       * @since 7.2.0 Detects a `.git` file, as used by Git worktrees and submodules.
 196       *
 197       * @param string $context The filesystem path to check, in addition to ABSPATH.
 198       * @return bool True if a VCS checkout was discovered at `$context` or ABSPATH,
 199       *              or anywhere higher. False otherwise.
 200       */
 201  	public function is_vcs_checkout( $context ) {
 202          $context_dirs = array( untrailingslashit( $context ) );
 203          if ( ABSPATH !== $context ) {
 204              $context_dirs[] = untrailingslashit( ABSPATH );
 205          }
 206  
 207          $vcs_dirs   = array( '.svn', '.git', '.hg', '.bzr' );
 208          $check_dirs = array();
 209  
 210          foreach ( $context_dirs as $context_dir ) {
 211              // Walk up from $context_dir to the root.
 212              do {
 213                  $check_dirs[] = $context_dir;
 214  
 215                  // Once we've hit '/' or 'C:\', we need to stop. dirname will keep returning the input here.
 216                  if ( dirname( $context_dir ) === $context_dir ) {
 217                      break;
 218                  }
 219  
 220                  // Continue one level at a time.
 221              } while ( $context_dir = dirname( $context_dir ) );
 222          }
 223  
 224          $check_dirs = array_unique( $check_dirs );
 225          $checkout   = false;
 226  
 227          // Search all directories we've found for evidence of version control.
 228          foreach ( $vcs_dirs as $vcs_dir ) {
 229              foreach ( $check_dirs as $check_dir ) {
 230                  if ( ! $this->is_allowed_dir( $check_dir ) ) {
 231                      continue;
 232                  }
 233  
 234                  // In a Git worktree or submodule, `.git` is a file rather than a directory.
 235                  $checkout = file_exists( rtrim( $check_dir, '\\/' ) . "/$vcs_dir" );
 236                  if ( $checkout ) {
 237                      break 2;
 238                  }
 239              }
 240          }
 241  
 242          /**
 243           * Filters whether the automatic updater should consider a filesystem
 244           * location to be potentially managed by a version control system.
 245           *
 246           * @since 3.7.0
 247           *
 248           * @param bool   $checkout Whether a VCS checkout was discovered at `$context`
 249           *                         or ABSPATH, or anywhere higher.
 250           * @param string $context  The filesystem context (a path) against which
 251           *                         filesystem status should be checked.
 252           */
 253          return apply_filters( 'automatic_updates_is_vcs_checkout', $checkout, $context );
 254      }
 255  
 256      /**
 257       * Tests to see if we can and should update a specific item.
 258       *
 259       * @since 3.7.0
 260       *
 261       * @global wpdb $wpdb WordPress database abstraction object.
 262       *
 263       * @param string $type    The type of update being checked: 'core', 'theme',
 264       *                        'plugin', 'translation'.
 265       * @param object $item    The update offer.
 266       * @param string $context The filesystem context (a path) against which filesystem
 267       *                        access and status should be checked.
 268       * @return bool True if the item should be updated, false otherwise.
 269       *
 270       * @phpstan-param 'core'|'theme'|'plugin'|'translation' $type
 271       * @phpstan-param (Core_Update_Offer|Plugin_Update_Offer|Theme_Update_Offer|Translation_Update_Offer) $item
 272       */
 273  	public function should_update( $type, $item, $context ) {
 274          // Used to see if WP_Filesystem is set up to allow unattended updates.
 275          $skin = new Automatic_Upgrader_Skin();
 276  
 277          if ( $this->is_disabled() ) {
 278              return false;
 279          }
 280  
 281          // Only relax the filesystem checks when the update doesn't include new files.
 282          $allow_relaxed_file_ownership = false;
 283          if ( 'core' === $type && isset( $item->new_files ) && ! $item->new_files ) {
 284              $allow_relaxed_file_ownership = true;
 285          }
 286  
 287          // If we can't do an auto core update, we may still be able to email the user.
 288          if ( ! $skin->request_filesystem_credentials( false, $context, $allow_relaxed_file_ownership )
 289              || $this->is_vcs_checkout( $context )
 290          ) {
 291              if ( 'core' === $type ) {
 292                  $this->send_core_update_notification_email( $item );
 293              }
 294              return false;
 295          }
 296  
 297          /*
 298           * Next up, is this an item we can update?
 299           *
 300           * The inline @phpstan-var tags narrow $item by $type. This should be replaced with a conditional
 301           * parameter type once PHPStan supports narrowing nested conditional parameter types.
 302           */
 303          if ( 'core' === $type ) {
 304              /** @phpstan-var Core_Update_Offer $item */
 305              $update = Core_Upgrader::should_update_to_version( $item->current );
 306          } elseif ( 'plugin' === $type || 'theme' === $type ) {
 307              /** @phpstan-var (Plugin_Update_Offer|Theme_Update_Offer) $item */
 308              $update = ! empty( $item->autoupdate );
 309  
 310              if ( ! $update && wp_is_auto_update_enabled_for_type( $type ) ) {
 311                  // Check if the site admin has enabled auto-updates by default for the specific item.
 312                  $auto_updates = (array) get_site_option( "auto_update_{$type}s", array() );
 313                  $update       = in_array( $item->{$type}, $auto_updates, true );
 314              }
 315          } else {
 316              $update = ! empty( $item->autoupdate );
 317  
 318              if ( $update && wp_is_translation_update_deferred( $item ) ) {
 319                  $update = false;
 320              }
 321          }
 322  
 323          // If the `disable_autoupdate` flag is set, override any user-choice, but allow filters.
 324          if ( ! empty( $item->disable_autoupdate ) ) {
 325              $update = false;
 326          }
 327  
 328          /**
 329           * Filters whether to automatically update core, a plugin, a theme, or a language.
 330           *
 331           * The dynamic portion of the hook name, `$type`, refers to the type of update
 332           * being checked.
 333           *
 334           * Possible hook names include:
 335           *
 336           *  - `auto_update_core`
 337           *  - `auto_update_plugin`
 338           *  - `auto_update_theme`
 339           *  - `auto_update_translation`
 340           *
 341           * Since WordPress 3.7, minor and development versions of core, and translations have
 342           * been auto-updated by default. New installs on WordPress 5.6 or higher will also
 343           * auto-update major versions by default. Starting in 5.6, older sites can opt-in to
 344           * major version auto-updates, and auto-updates for plugins and themes.
 345           *
 346           * See the {@see 'allow_dev_auto_core_updates'}, {@see 'allow_minor_auto_core_updates'},
 347           * and {@see 'allow_major_auto_core_updates'} filters for a more straightforward way to
 348           * adjust core updates.
 349           *
 350           * @since 3.7.0
 351           * @since 5.5.0 The `$update` parameter accepts the value of null.
 352           *
 353           * @param bool|null $update Whether to update. The value of null is internally used
 354           *                          to detect whether nothing has hooked into this filter.
 355           * @param object    $item   The update offer.
 356           */
 357          $update = apply_filters( "auto_update_{$type}", $update, $item );
 358  
 359          if ( ! $update ) {
 360              if ( 'core' === $type ) {
 361                  $this->send_core_update_notification_email( $item );
 362              }
 363              return false;
 364          }
 365  
 366          // If it's a core update, are we actually compatible with its requirements?
 367          if ( 'core' === $type ) {
 368              global $wpdb;
 369  
 370              /** @phpstan-var Core_Update_Offer $item */
 371              $php_compat = version_compare( PHP_VERSION, $item->php_version, '>=' );
 372              if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) ) {
 373                  $mysql_compat = true;
 374              } else {
 375                  $mysql_compat = version_compare( $wpdb->db_version(), $item->mysql_version, '>=' );
 376              }
 377  
 378              if ( ! $php_compat || ! $mysql_compat ) {
 379                  return false;
 380              }
 381          }
 382  
 383          // If updating a plugin or theme, ensure the minimum PHP version requirements are satisfied.
 384          if ( in_array( $type, array( 'plugin', 'theme' ), true ) ) {
 385              /** @phpstan-var (Plugin_Update_Offer|Theme_Update_Offer) $item */
 386              if ( ! empty( $item->requires_php ) && version_compare( PHP_VERSION, $item->requires_php, '<' ) ) {
 387                  return false;
 388              }
 389          }
 390  
 391          return true;
 392      }
 393  
 394      /**
 395       * Notifies an administrator of a core update.
 396       *
 397       * @since 3.7.0
 398       *
 399       * @param object $item The update offer.
 400       * @return bool True if the site administrator is notified of a core update,
 401       *              false otherwise.
 402       */
 403  	protected function send_core_update_notification_email( $item ) {
 404          $notified = get_site_option( 'auto_core_update_notified' );
 405  
 406          // Don't notify if we've already notified the same email address of the same version.
 407          if ( $notified
 408              && get_site_option( 'admin_email' ) === $notified['email']
 409              && $notified['version'] === $item->current
 410          ) {
 411              return false;
 412          }
 413  
 414          // See if we need to notify users of a core update.
 415          $notify = ! empty( $item->notify_email );
 416  
 417          /**
 418           * Filters whether to notify the site administrator of a new core update.
 419           *
 420           * By default, administrators are notified when the update offer received
 421           * from WordPress.org sets a particular flag. This allows some discretion
 422           * in if and when to notify.
 423           *
 424           * This filter is only evaluated once per release. If the same email address
 425           * was already notified of the same new version, WordPress won't repeatedly
 426           * email the administrator.
 427           *
 428           * This filter is also used on about.php to check if a plugin has disabled
 429           * these notifications.
 430           *
 431           * @since 3.7.0
 432           *
 433           * @param bool   $notify Whether the site administrator is notified.
 434           * @param object $item   The update offer.
 435           */
 436          if ( ! apply_filters( 'send_core_update_notification_email', $notify, $item ) ) {
 437              return false;
 438          }
 439  
 440          $this->send_email( 'manual', $item );
 441          return true;
 442      }
 443  
 444      /**
 445       * Updates an item, if appropriate.
 446       *
 447       * @since 3.7.0
 448       *
 449       * @param string $type The type of update being checked: 'core', 'theme', 'plugin', 'translation'.
 450       * @param object $item The update offer.
 451       * @return WP_Error|bool|string|array|null False if the item should not be updated, otherwise the result
 452       *                                         from the upgrader: the new WordPress version for core, true for
 453       *                                         a successful plugin or theme update, the installation result for
 454       *                                         a translation, or a WP_Error on failure. Null for a plugin, theme,
 455       *                                         or translation if the update failed before the package was
 456       *                                         installed.
 457       *
 458       * @phpstan-param 'core'|'theme'|'plugin'|'translation' $type
 459       * @phpstan-param (Core_Update_Offer|Plugin_Update_Offer|Theme_Update_Offer|Translation_Update_Offer) $item
 460       * @phpstan-return (
 461       *     $type is 'core' ? string|false|WP_Error : (
 462       *         $type is 'translation' ? array<mixed>|bool|WP_Error|null : bool|WP_Error|null
 463       *     )
 464       * )
 465       */
 466  	public function update( $type, $item ) {
 467          $skin = new Automatic_Upgrader_Skin();
 468  
 469          /*
 470           * The inline @phpstan-var tags narrow $item by $type. This should be replaced with a conditional
 471           * parameter type once PHPStan supports narrowing nested conditional parameter types.
 472           */
 473          $upgrader = null;
 474          $context  = null;
 475          switch ( $type ) {
 476              case 'core':
 477                  /** @phpstan-var Core_Update_Offer $item */
 478                  // The Core upgrader doesn't use the Upgrader's skin during the actual main part of the upgrade, instead, firing a filter.
 479                  add_filter( 'update_feedback', array( $skin, 'feedback' ) );
 480                  $upgrader = new Core_Upgrader( $skin );
 481                  $context  = ABSPATH;
 482                  break;
 483              case 'plugin':
 484                  /** @phpstan-var Plugin_Update_Offer $item */
 485                  $upgrader = new Plugin_Upgrader( $skin );
 486                  $context  = WP_PLUGIN_DIR; // We don't support custom Plugin directories, or updates for WPMU_PLUGIN_DIR.
 487                  break;
 488              case 'theme':
 489                  /** @phpstan-var Theme_Update_Offer $item */
 490                  $upgrader = new Theme_Upgrader( $skin );
 491                  $context  = get_theme_root( $item->theme );
 492                  break;
 493              case 'translation':
 494                  /** @phpstan-var Translation_Update_Offer $item */
 495                  $upgrader = new Language_Pack_Upgrader( $skin );
 496                  $context  = WP_CONTENT_DIR; // WP_LANG_DIR;
 497                  break;
 498          }
 499  
 500          // Determine whether we can and should perform this update.
 501          if ( ! $this->should_update( $type, $item, $context ) ) {
 502              return false;
 503          }
 504  
 505          /**
 506           * Fires immediately prior to an auto-update.
 507           *
 508           * @since 4.4.0
 509           *
 510           * @param string $type    The type of update being checked: 'core', 'theme', 'plugin', or 'translation'.
 511           * @param object $item    The update offer.
 512           * @param string $context The filesystem context (a path) against which filesystem access and status
 513           *                        should be checked.
 514           */
 515          do_action( 'pre_auto_update', $type, $item, $context );
 516  
 517          $item_name     = null;
 518          $upgrader_item = $item;
 519          switch ( $type ) {
 520              case 'core':
 521                  /** @phpstan-var Core_Update_Offer $item */
 522                  /* translators: %s: WordPress version. */
 523                  $skin->feedback( __( 'Updating to WordPress %s' ), $item->version );
 524                  /* translators: %s: WordPress version. */
 525                  $item_name = sprintf( __( 'WordPress %s' ), $item->version );
 526                  break;
 527              case 'theme':
 528                  /** @phpstan-var Theme_Update_Offer $item */
 529                  $upgrader_item = $item->theme;
 530                  $theme         = wp_get_theme( $upgrader_item );
 531                  $item_name     = $theme->get( 'Name' );
 532                  // Add the current version so that it can be reported in the notification email.
 533                  $item->current_version = $theme->get( 'Version' );
 534                  if ( empty( $item->current_version ) ) {
 535                      $item->current_version = false;
 536                  }
 537                  /* translators: %s: Theme name. */
 538                  $skin->feedback( __( 'Updating theme: %s' ), $item_name );
 539                  break;
 540              case 'plugin':
 541                  /** @phpstan-var Plugin_Update_Offer $item */
 542                  $upgrader_item = $item->plugin;
 543                  $plugin_data   = get_plugin_data( $context . '/' . $upgrader_item );
 544                  $item_name     = $plugin_data['Name'];
 545                  // Add the current version so that it can be reported in the notification email.
 546                  $item->current_version = $plugin_data['Version'];
 547                  if ( empty( $item->current_version ) ) {
 548                      $item->current_version = false;
 549                  }
 550                  /* translators: %s: Plugin name. */
 551                  $skin->feedback( __( 'Updating plugin: %s' ), $item_name );
 552                  break;
 553              case 'translation':
 554                  /** @phpstan-var Translation_Update_Offer $item */
 555                  /** @var Language_Pack_Upgrader $upgrader */
 556                  $language_item_name = $upgrader->get_name_for_update( $item );
 557                  /* translators: %s: Project name (plugin, theme, or WordPress). */
 558                  $item_name = sprintf( __( 'Translations for %s' ), $language_item_name );
 559                  /* translators: 1: Project name (plugin, theme, or WordPress), 2: Language. */
 560                  $skin->feedback( sprintf( __( 'Updating translations for %1$s (%2$s)&#8230;' ), $language_item_name, $item->language ) );
 561                  break;
 562          }
 563  
 564          $allow_relaxed_file_ownership = false;
 565          if ( 'core' === $type && isset( $item->new_files ) && ! $item->new_files ) {
 566              $allow_relaxed_file_ownership = true;
 567          }
 568  
 569          $was_active = null;
 570          $is_debug   = WP_DEBUG && WP_DEBUG_LOG;
 571          if ( 'plugin' === $type ) {
 572              /** @phpstan-var Plugin_Update_Offer $item */
 573              /** @var string $upgrader_item */
 574              $was_active = is_plugin_active( $upgrader_item );
 575              if ( $is_debug ) {
 576                  error_log( '    Upgrading plugin ' . var_export( $item->slug, true ) . '...' );
 577              }
 578          }
 579  
 580          if ( 'theme' === $type && $is_debug ) {
 581              /** @phpstan-var Theme_Update_Offer $item */
 582              error_log( '    Upgrading theme ' . var_export( $item->theme, true ) . '...' );
 583          }
 584  
 585          /*
 586           * Enable maintenance mode before upgrading the plugin or theme.
 587           *
 588           * This avoids potential non-fatal errors being detected
 589           * while scraping for a fatal error if some files are still
 590           * being moved.
 591           *
 592           * While these checks are intended only for plugins,
 593           * maintenance mode is enabled for all upgrade types as any
 594           * update could contain an error or warning, which could cause
 595           * the scrape to miss a fatal error in the plugin update.
 596           */
 597          if ( 'translation' !== $type ) {
 598              $upgrader->maintenance_mode( true );
 599          }
 600  
 601          // Boom, this site's about to get a whole new splash of paint!
 602          $upgrade_result = $upgrader->upgrade(
 603              $upgrader_item,
 604              array(
 605                  'clear_update_cache'           => false,
 606                  // Always use partial builds if possible for core updates.
 607                  'pre_check_md5'                => false,
 608                  // Only available for core updates.
 609                  'attempt_rollback'             => true,
 610                  // Allow relaxed file ownership in some scenarios.
 611                  'allow_relaxed_file_ownership' => $allow_relaxed_file_ownership,
 612              )
 613          );
 614  
 615          /*
 616           * After WP_Upgrader::upgrade() completes, maintenance mode is disabled.
 617           *
 618           * Re-enable maintenance mode while attempting to detect fatal errors
 619           * and potentially rolling back.
 620           *
 621           * This avoids errors if the site is visited while fatal errors exist
 622           * or while files are still being moved.
 623           */
 624          if ( 'translation' !== $type ) {
 625              $upgrader->maintenance_mode( true );
 626          }
 627  
 628          // If the filesystem is unavailable, false is returned.
 629          if ( false === $upgrade_result ) {
 630              $upgrade_result = new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
 631          }
 632  
 633          if ( 'core' === $type ) {
 634              if ( is_wp_error( $upgrade_result )
 635                  && ( 'up_to_date' === $upgrade_result->get_error_code()
 636                      || 'locked' === $upgrade_result->get_error_code() )
 637              ) {
 638                  // Allow visitors to browse the site again.
 639                  $upgrader->maintenance_mode( false );
 640  
 641                  /*
 642                   * These aren't actual errors, treat it as a skipped-update instead
 643                   * to avoid triggering the post-core update failure routines.
 644                   */
 645                  return false;
 646              }
 647  
 648              // Core doesn't output this, so let's append it, so we don't get confused.
 649              if ( is_wp_error( $upgrade_result ) ) {
 650                  $upgrade_result->add( 'installation_failed', __( 'Installation failed.' ) );
 651                  $skin->error( $upgrade_result );
 652              } else {
 653                  $skin->feedback( __( 'WordPress updated successfully.' ) );
 654              }
 655          }
 656  
 657          if ( 'theme' === $type && $is_debug ) {
 658              /** @phpstan-var Theme_Update_Offer $item */
 659              error_log( '    Theme ' . var_export( $item->theme, true ) . ' has been upgraded.' );
 660          }
 661  
 662          if ( 'plugin' === $type ) {
 663              /** @phpstan-var Plugin_Update_Offer $item */
 664              /** @var string $upgrader_item */
 665              if ( $is_debug ) {
 666                  error_log( '    Plugin ' . var_export( $item->slug, true ) . ' has been upgraded.' );
 667                  if ( is_plugin_inactive( $upgrader_item ) ) {
 668                      error_log( '    ' . var_export( $upgrader_item, true ) . ' is inactive and will not be checked for fatal errors.' );
 669                  }
 670              }
 671  
 672              if ( $was_active && ! is_wp_error( $upgrade_result ) ) {
 673  
 674                  /*
 675                   * The usual time limit is five minutes. However, as a loopback request
 676                   * is about to be performed, increase the time limit to account for this.
 677                   */
 678                  if ( function_exists( 'set_time_limit' ) ) {
 679                      set_time_limit( 10 * MINUTE_IN_SECONDS );
 680                  }
 681  
 682                  /*
 683                   * Avoids a race condition when there are 2 sequential plugins that have
 684                   * fatal errors. It seems a slight delay is required for the loopback to
 685                   * use the updated plugin code in the request. This can cause the second
 686                   * plugin's fatal error checking to be inaccurate, and may also affect
 687                   * subsequent plugin checks.
 688                   */
 689                  sleep( 2 );
 690  
 691                  if ( $this->has_fatal_error() ) {
 692                      $upgrade_result = new WP_Error();
 693                      $temp_backup    = array(
 694                          array(
 695                              'dir'  => 'plugins',
 696                              'slug' => $item->slug,
 697                              'src'  => WP_PLUGIN_DIR,
 698                          ),
 699                      );
 700  
 701                      $backup_restored = $upgrader->restore_temp_backup( $temp_backup );
 702                      if ( is_wp_error( $backup_restored ) ) {
 703                          $upgrade_result->add(
 704                              'plugin_update_fatal_error_rollback_failed',
 705                              sprintf(
 706                                  /* translators: %s: The plugin's slug. */
 707                                  __( "The update for '%s' contained a fatal error. The previously installed version could not be restored." ),
 708                                  $item->slug
 709                              )
 710                          );
 711  
 712                          $upgrade_result->merge_from( $backup_restored );
 713                      } else {
 714                          $upgrade_result->add(
 715                              'plugin_update_fatal_error_rollback_successful',
 716                              sprintf(
 717                                  /* translators: %s: The plugin's slug. */
 718                                  __( "The update for '%s' contained a fatal error. The previously installed version has been restored." ),
 719                                  $item->slug
 720                              )
 721                          );
 722  
 723                          $backup_deleted = $upgrader->delete_temp_backup( $temp_backup );
 724                          if ( is_wp_error( $backup_deleted ) ) {
 725                              $upgrade_result->merge_from( $backup_deleted );
 726                          }
 727                      }
 728  
 729                      if ( null !== $this->fatal_error_message ) {
 730                          $upgrade_result->add( 'plugin_update_fatal_error', $this->fatal_error_message );
 731                      }
 732  
 733                      /*
 734                       * Should emails not be working, log the message(s) so that
 735                       * the log file contains context for the fatal error,
 736                       * and whether a rollback was performed.
 737                       *
 738                       * `trigger_error()` is not used as it outputs a stack trace
 739                       * to this location rather than to the fatal error, which will
 740                       * appear above this entry in the log file.
 741                       */
 742                      if ( $is_debug ) {
 743                          error_log( '    ' . implode( "\n", $upgrade_result->get_error_messages() ) );
 744                      }
 745                  } elseif ( $is_debug ) {
 746                      error_log( '    The update for ' . var_export( $item->slug, true ) . ' has no fatal errors.' );
 747                  }
 748              }
 749          }
 750  
 751          // All processes are complete. Allow visitors to browse the site again.
 752          if ( 'translation' !== $type ) {
 753              $upgrader->maintenance_mode( false );
 754          }
 755  
 756          $this->update_results[ $type ][] = (object) array(
 757              'item'     => $item,
 758              'result'   => $upgrade_result,
 759              'name'     => $item_name,
 760              'messages' => $skin->get_upgrade_messages(),
 761          );
 762  
 763          return $upgrade_result;
 764      }
 765  
 766      /**
 767       * Kicks off the background update process, looping through all pending updates.
 768       *
 769       * @since 3.7.0
 770       */
 771  	public function run() {
 772          if ( $this->is_disabled() ) {
 773              return;
 774          }
 775  
 776          if ( ! is_main_network() || ! is_main_site() ) {
 777              return;
 778          }
 779  
 780          if ( ! WP_Upgrader::create_lock( 'auto_updater' ) ) {
 781              return;
 782          }
 783  
 784          $is_debug = WP_DEBUG && WP_DEBUG_LOG;
 785  
 786          if ( $is_debug ) {
 787              error_log( 'Automatic updates starting...' );
 788          }
 789  
 790          // Don't automatically run these things, as we'll handle it ourselves.
 791          remove_action( 'upgrader_process_complete', array( 'Language_Pack_Upgrader', 'async_upgrade' ), 20 );
 792          remove_action( 'upgrader_process_complete', 'wp_version_check' );
 793          remove_action( 'upgrader_process_complete', 'wp_update_plugins' );
 794          remove_action( 'upgrader_process_complete', 'wp_update_themes' );
 795  
 796          // Next, plugins.
 797          wp_update_plugins(); // Check for plugin updates.
 798          $plugin_updates = get_site_transient( 'update_plugins' );
 799          if ( $plugin_updates && ! empty( $plugin_updates->response ) ) {
 800              if ( $is_debug ) {
 801                  error_log( '  Automatic plugin updates starting...' );
 802              }
 803  
 804              foreach ( $plugin_updates->response as $plugin ) {
 805                  $this->update( 'plugin', $plugin );
 806              }
 807  
 808              // Force refresh of plugin update information.
 809              wp_clean_plugins_cache();
 810  
 811              if ( $is_debug ) {
 812                  error_log( '  Automatic plugin updates complete.' );
 813              }
 814          }
 815  
 816          // Next, those themes we all love.
 817          wp_update_themes();  // Check for theme updates.
 818          $theme_updates = get_site_transient( 'update_themes' );
 819          if ( $theme_updates && ! empty( $theme_updates->response ) ) {
 820              if ( $is_debug ) {
 821                  error_log( '  Automatic theme updates starting...' );
 822              }
 823  
 824              foreach ( $theme_updates->response as $theme ) {
 825                  $this->update( 'theme', (object) $theme );
 826              }
 827              // Force refresh of theme update information.
 828              wp_clean_themes_cache();
 829  
 830              if ( $is_debug ) {
 831                  error_log( '  Automatic theme updates complete.' );
 832              }
 833          }
 834  
 835          if ( $is_debug ) {
 836              error_log( 'Automatic updates complete.' );
 837          }
 838  
 839          // Next, process any core update.
 840          wp_version_check(); // Check for core updates.
 841          $core_update = find_core_auto_update();
 842  
 843          if ( $core_update ) {
 844              $this->update( 'core', $core_update );
 845          }
 846  
 847          /*
 848           * Clean up, and check for any pending translations.
 849           * (Core_Upgrader checks for core updates.)
 850           */
 851          $theme_stats = array();
 852          if ( isset( $this->update_results['theme'] ) ) {
 853              foreach ( $this->update_results['theme'] as $upgrade ) {
 854                  $theme_stats[ $upgrade->item->theme ] = ( true === $upgrade->result );
 855              }
 856          }
 857          wp_update_themes( $theme_stats ); // Check for theme updates.
 858  
 859          $plugin_stats = array();
 860          if ( isset( $this->update_results['plugin'] ) ) {
 861              foreach ( $this->update_results['plugin'] as $upgrade ) {
 862                  $plugin_stats[ $upgrade->item->plugin ] = ( true === $upgrade->result );
 863              }
 864          }
 865          wp_update_plugins( $plugin_stats ); // Check for plugin updates.
 866  
 867          // Finally, process any new translations.
 868          $language_updates = wp_get_translation_updates();
 869          if ( $language_updates ) {
 870              foreach ( $language_updates as $update ) {
 871                  $this->update( 'translation', $update );
 872              }
 873  
 874              // Clear existing caches.
 875              wp_clean_update_cache();
 876  
 877              wp_version_check();  // Check for core updates.
 878              wp_update_themes();  // Check for theme updates.
 879              wp_update_plugins(); // Check for plugin updates.
 880          }
 881  
 882          // Send debugging email to admin for all development installations.
 883          if ( ! empty( $this->update_results ) ) {
 884              $development_version = str_contains( wp_get_wp_version(), '-' );
 885  
 886              /**
 887               * Filters whether to send a debugging email for each automatic background update.
 888               *
 889               * @since 3.7.0
 890               *
 891               * @param bool $development_version By default, emails are sent if the
 892               *                                  install is a development version.
 893               *                                  Return false to avoid the email.
 894               */
 895              if ( apply_filters( 'automatic_updates_send_debug_email', $development_version ) ) {
 896                  $this->send_debug_email();
 897              }
 898  
 899              if ( ! empty( $this->update_results['core'] ) ) {
 900                  $this->after_core_update( $this->update_results['core'][0] );
 901              } elseif ( ! empty( $this->update_results['plugin'] ) || ! empty( $this->update_results['theme'] ) ) {
 902                  $this->after_plugin_theme_update( $this->update_results );
 903              }
 904  
 905              /**
 906               * Fires after all automatic updates have run.
 907               *
 908               * @since 3.8.0
 909               *
 910               * @param array $update_results The results of all attempted updates.
 911               */
 912              do_action( 'automatic_updates_complete', $this->update_results );
 913          }
 914  
 915          WP_Upgrader::release_lock( 'auto_updater' );
 916      }
 917  
 918      /**
 919       * Checks whether to send an email and avoid processing future updates after
 920       * attempting a core update.
 921       *
 922       * @since 3.7.0
 923       *
 924       * @param object $update_result The result of the core update. Includes the update offer and result.
 925       */
 926  	protected function after_core_update( $update_result ) {
 927          $wp_version = wp_get_wp_version();
 928  
 929          $core_update = $update_result->item;
 930          $result      = $update_result->result;
 931  
 932          if ( ! is_wp_error( $result ) ) {
 933              $this->send_email( 'success', $core_update );
 934              return;
 935          }
 936  
 937          $error_code = $result->get_error_code();
 938  
 939          /*
 940           * Any of these WP_Error codes are critical failures, as in they occurred after we started to copy core files.
 941           * We should not try to perform a background update again until there is a successful one-click update performed by the user.
 942           */
 943          $critical = false;
 944          if ( 'disk_full' === $error_code || str_contains( $error_code, '__copy_dir' ) ) {
 945              $critical = true;
 946          } elseif ( 'rollback_was_required' === $error_code && is_wp_error( $result->get_error_data()->rollback ) ) {
 947              // A rollback is only critical if it failed too.
 948              $critical        = true;
 949              $rollback_result = $result->get_error_data()->rollback;
 950          } elseif ( str_contains( $error_code, 'do_rollback' ) ) {
 951              $critical = true;
 952          }
 953  
 954          if ( $critical ) {
 955              $critical_data = array(
 956                  'attempted'  => $core_update->current,
 957                  'current'    => $wp_version,
 958                  'error_code' => $error_code,
 959                  'error_data' => $result->get_error_data(),
 960                  'timestamp'  => time(),
 961                  'critical'   => true,
 962              );
 963              if ( isset( $rollback_result ) ) {
 964                  $critical_data['rollback_code'] = $rollback_result->get_error_code();
 965                  $critical_data['rollback_data'] = $rollback_result->get_error_data();
 966              }
 967              update_site_option( 'auto_core_update_failed', $critical_data );
 968              $this->send_email( 'critical', $core_update, $result );
 969              return;
 970          }
 971  
 972          /*
 973           * Any other WP_Error code (like download_failed or files_not_writable) occurs before
 974           * we tried to copy over core files. Thus, the failures are early and graceful.
 975           *
 976           * We should avoid trying to perform a background update again for the same version.
 977           * But we can try again if another version is released.
 978           *
 979           * For certain 'transient' failures, like download_failed, we should allow retries.
 980           * In fact, let's schedule a special update for an hour from now. (It's possible
 981           * the issue could actually be on WordPress.org's side.) If that one fails, then email.
 982           */
 983          $send               = true;
 984          $transient_failures = array( 'incompatible_archive', 'download_failed', 'insane_distro', 'locked' );
 985          if ( in_array( $error_code, $transient_failures, true ) && ! get_site_option( 'auto_core_update_failed' ) ) {
 986              wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'wp_maybe_auto_update' );
 987              $send = false;
 988          }
 989  
 990          $notified = get_site_option( 'auto_core_update_notified' );
 991  
 992          // Don't notify if we've already notified the same email address of the same version of the same notification type.
 993          if ( $notified
 994              && 'fail' === $notified['type']
 995              && get_site_option( 'admin_email' ) === $notified['email']
 996              && $notified['version'] === $core_update->current
 997          ) {
 998              $send = false;
 999          }
1000  
1001          update_site_option(
1002              'auto_core_update_failed',
1003              array(
1004                  'attempted'  => $core_update->current,
1005                  'current'    => $wp_version,
1006                  'error_code' => $error_code,
1007                  'error_data' => $result->get_error_data(),
1008                  'timestamp'  => time(),
1009                  'retry'      => in_array( $error_code, $transient_failures, true ),
1010              )
1011          );
1012  
1013          if ( $send ) {
1014              $this->send_email( 'fail', $core_update, $result );
1015          }
1016      }
1017  
1018      /**
1019       * Sends an email upon the completion or failure of a background core update.
1020       *
1021       * @since 3.7.0
1022       *
1023       * @param string $type        The type of email to send. Can be one of 'success', 'fail', 'manual', 'critical'.
1024       * @param object $core_update The update offer that was attempted.
1025       * @param mixed  $result      Optional. The result for the core update. Can be WP_Error.
1026       */
1027  	protected function send_email( $type, $core_update, $result = null ) {
1028          update_site_option(
1029              'auto_core_update_notified',
1030              array(
1031                  'type'      => $type,
1032                  'email'     => get_site_option( 'admin_email' ),
1033                  'version'   => $core_update->current,
1034                  'timestamp' => time(),
1035              )
1036          );
1037  
1038          $next_user_core_update = get_preferred_from_update_core();
1039  
1040          // If the update transient is empty, use the update we just performed.
1041          if ( ! $next_user_core_update ) {
1042              $next_user_core_update = $core_update;
1043          }
1044  
1045          if ( 'upgrade' === $next_user_core_update->response
1046              && version_compare( $next_user_core_update->version, $core_update->version, '>' )
1047          ) {
1048              $newer_version_available = true;
1049          } else {
1050              $newer_version_available = false;
1051          }
1052  
1053          /**
1054           * Filters whether to send an email following an automatic background core update.
1055           *
1056           * @since 3.7.0
1057           *
1058           * @param bool   $send        Whether to send the email. Default true.
1059           * @param string $type        The type of email to send. Can be one of
1060           *                            'success', 'fail', 'critical'.
1061           * @param object $core_update The update offer that was attempted.
1062           * @param mixed  $result      The result for the core update. Can be WP_Error.
1063           */
1064          if ( 'manual' !== $type && ! apply_filters( 'auto_core_update_send_email', true, $type, $core_update, $result ) ) {
1065              return;
1066          }
1067  
1068          $admin_user = get_user_by( 'email', get_site_option( 'admin_email' ) );
1069  
1070          if ( $admin_user ) {
1071              $switched_locale = switch_to_user_locale( $admin_user->ID );
1072          } else {
1073              $switched_locale = switch_to_locale( get_locale() );
1074          }
1075  
1076          switch ( $type ) {
1077              case 'success': // We updated.
1078                  /* translators: Site updated notification email subject. 1: Site title, 2: WordPress version. */
1079                  $subject = __( '[%1$s] Your site has updated to WordPress %2$s' );
1080                  break;
1081  
1082              case 'fail':   // We tried to update but couldn't.
1083              case 'manual': // We can't update (and made no attempt).
1084                  /* translators: Update available notification email subject. 1: Site title, 2: WordPress version. */
1085                  $subject = __( '[%1$s] WordPress %2$s is available. Please update!' );
1086                  break;
1087  
1088              case 'critical': // We tried to update, started to copy files, then things went wrong.
1089                  /* translators: Site down notification email subject. 1: Site title. */
1090                  $subject = __( '[%1$s] URGENT: Your site may be down due to a failed update' );
1091                  break;
1092  
1093              default:
1094                  return;
1095          }
1096  
1097          // If the auto-update is not to the latest version, say that the current version of WP is available instead.
1098          $version = 'success' === $type ? $core_update->current : $next_user_core_update->current;
1099          $subject = sprintf( $subject, wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $version );
1100  
1101          $body = '';
1102  
1103          switch ( $type ) {
1104              case 'success':
1105                  $body .= sprintf(
1106                      /* translators: 1: Home URL, 2: WordPress version. */
1107                      __( 'Howdy! Your site at %1$s has been updated automatically to WordPress %2$s.' ),
1108                      home_url(),
1109                      $core_update->current
1110                  );
1111                  $body .= "\n\n";
1112                  if ( ! $newer_version_available ) {
1113                      $body .= __( 'No further action is needed on your part.' ) . ' ';
1114                  }
1115  
1116                  // Can only reference the About screen if their update was successful.
1117                  list( $about_version ) = explode( '-', $core_update->current, 2 );
1118                  /* translators: %s: WordPress version. */
1119                  $body .= sprintf( __( 'For more on version %s, see the About WordPress screen:' ), $about_version );
1120                  $body .= "\n" . admin_url( 'about.php' );
1121  
1122                  if ( $newer_version_available ) {
1123                      /* translators: %s: WordPress latest version. */
1124                      $body .= "\n\n" . sprintf( __( 'WordPress %s is also now available.' ), $next_user_core_update->current ) . ' ';
1125                      $body .= __( 'Updating is easy and only takes a few moments:' );
1126                      $body .= "\n" . network_admin_url( 'update-core.php' );
1127                  }
1128  
1129                  break;
1130  
1131              case 'fail':
1132              case 'manual':
1133                  $body .= sprintf(
1134                      /* translators: 1: Home URL, 2: WordPress version. */
1135                      __( 'Please update your site at %1$s to WordPress %2$s.' ),
1136                      home_url(),
1137                      $next_user_core_update->current
1138                  );
1139  
1140                  $body .= "\n\n";
1141  
1142                  /*
1143                   * Don't show this message if there is a newer version available.
1144                   * Potential for confusion, and also not useful for them to know at this point.
1145                   */
1146                  if ( 'fail' === $type && ! $newer_version_available ) {
1147                      $body .= __( 'An attempt was made, but your site could not be updated automatically.' ) . ' ';
1148                  }
1149  
1150                  $body .= __( 'Updating is easy and only takes a few moments:' );
1151                  $body .= "\n" . network_admin_url( 'update-core.php' );
1152                  break;
1153  
1154              case 'critical':
1155                  if ( $newer_version_available ) {
1156                      $body .= sprintf(
1157                          /* translators: 1: Home URL, 2: WordPress version. */
1158                          __( 'Your site at %1$s experienced a critical failure while trying to update WordPress to version %2$s.' ),
1159                          home_url(),
1160                          $core_update->current
1161                      );
1162                  } else {
1163                      $body .= sprintf(
1164                          /* translators: 1: Home URL, 2: WordPress latest version. */
1165                          __( 'Your site at %1$s experienced a critical failure while trying to update to the latest version of WordPress, %2$s.' ),
1166                          home_url(),
1167                          $core_update->current
1168                      );
1169                  }
1170  
1171                  $body .= "\n\n" . __( "This means your site may be offline or broken. Don't panic; this can be fixed." );
1172  
1173                  $body .= "\n\n" . __( "Please check out your site now. It's possible that everything is working. If it says you need to update, you should do so:" );
1174                  $body .= "\n" . network_admin_url( 'update-core.php' );
1175                  break;
1176          }
1177  
1178          $critical_support = 'critical' === $type && ! empty( $core_update->support_email );
1179          if ( $critical_support ) {
1180              // Support offer if available.
1181              $body .= "\n\n" . sprintf(
1182                  /* translators: %s: Support email address. */
1183                  __( 'The WordPress team is willing to help you. Forward this email to %s and the team will work with you to make sure your site is working.' ),
1184                  $core_update->support_email
1185              );
1186          } else {
1187              // Add a note about the support forums.
1188              $body .= "\n\n" . __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
1189              $body .= "\n" . __( 'https://wordpress.org/support/forums/' );
1190          }
1191  
1192          // Updates are important!
1193          if ( 'success' !== $type || $newer_version_available ) {
1194              $body .= "\n\n" . __( 'Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.' );
1195          }
1196  
1197          if ( $critical_support ) {
1198              $body .= ' ' . __( "Reach out to WordPress Core developers to ensure you'll never have this problem again." );
1199          }
1200  
1201          // If things are successful and we're now on the latest, mention plugins and themes if any are out of date.
1202          if ( 'success' === $type && ! $newer_version_available && ( get_plugin_updates() || get_theme_updates() ) ) {
1203              $body .= "\n\n" . __( 'You also have some plugins or themes with updates available. Update them now:' );
1204              $body .= "\n" . network_admin_url();
1205          }
1206  
1207          $body .= "\n\n" . __( 'The WordPress Team' ) . "\n";
1208  
1209          if ( 'critical' === $type && is_wp_error( $result ) ) {
1210              $body .= "\n***\n\n";
1211              /* translators: %s: WordPress version. */
1212              $body .= sprintf( __( 'Your site was running version %s.' ), get_bloginfo( 'version' ) );
1213              $body .= ' ' . __( 'Some data that describes the error your site encountered has been put together.' );
1214              $body .= ' ' . __( 'Your hosting company, support forum volunteers, or a friendly developer may be able to use this information to help you:' );
1215  
1216              /*
1217               * If we had a rollback and we're still critical, then the rollback failed too.
1218               * Loop through all errors (the main WP_Error, the update result, the rollback result) for code, data, etc.
1219               */
1220              if ( 'rollback_was_required' === $result->get_error_code() ) {
1221                  $errors = array( $result, $result->get_error_data()->update, $result->get_error_data()->rollback );
1222              } else {
1223                  $errors = array( $result );
1224              }
1225  
1226              foreach ( $errors as $error ) {
1227                  if ( ! is_wp_error( $error ) ) {
1228                      continue;
1229                  }
1230  
1231                  $error_code = $error->get_error_code();
1232                  /* translators: %s: Error code. */
1233                  $body .= "\n\n" . sprintf( __( 'Error code: %s' ), $error_code );
1234  
1235                  if ( 'rollback_was_required' === $error_code ) {
1236                      continue;
1237                  }
1238  
1239                  if ( $error->get_error_message() ) {
1240                      $body .= "\n" . $error->get_error_message();
1241                  }
1242  
1243                  $error_data = $error->get_error_data();
1244                  if ( $error_data ) {
1245                      $body .= "\n" . implode( ', ', (array) $error_data );
1246                  }
1247              }
1248  
1249              $body .= "\n";
1250          }
1251  
1252          $to      = get_site_option( 'admin_email' );
1253          $headers = '';
1254  
1255          $email = compact( 'to', 'subject', 'body', 'headers' );
1256  
1257          /**
1258           * Filters the email sent following an automatic background core update.
1259           *
1260           * @since 3.7.0
1261           *
1262           * @param array  $email {
1263           *     Array of email arguments that will be passed to wp_mail().
1264           *
1265           *     @type string $to      The email recipient. An array of emails
1266           *                            can be returned, as handled by wp_mail().
1267           *     @type string $subject The email's subject.
1268           *     @type string $body    The email message body.
1269           *     @type string $headers Any email headers, defaults to no headers.
1270           * }
1271           * @param string $type        The type of email being sent. Can be one of
1272           *                            'success', 'fail', 'manual', 'critical'.
1273           * @param object $core_update The update offer that was attempted.
1274           * @param mixed  $result      The result for the core update. Can be WP_Error.
1275           */
1276          $email = apply_filters( 'auto_core_update_email', $email, $type, $core_update, $result );
1277  
1278          wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
1279  
1280          if ( $switched_locale ) {
1281              restore_previous_locale();
1282          }
1283      }
1284  
1285      /**
1286       * Checks whether an email should be sent after attempting plugin or theme updates.
1287       *
1288       * @since 5.5.0
1289       *
1290       * @param array $update_results The results of update tasks.
1291       *
1292       * @phpstan-param array{
1293       *     core?: list<Core_Update_Result>,
1294       *     plugin?: list<Plugin_Update_Result>,
1295       *     theme?: list<Theme_Update_Result>,
1296       *     translation?: list<Translation_Update_Result>,
1297       * } $update_results
1298       */
1299  	protected function after_plugin_theme_update( $update_results ) {
1300          $successful_updates = array();
1301          $failed_updates     = array();
1302  
1303          if ( ! empty( $update_results['plugin'] ) ) {
1304              /**
1305               * Filters whether to send an email following an automatic background plugin update.
1306               *
1307               * @since 5.5.0
1308               * @since 5.5.1 Added the `$update_results` parameter.
1309               *
1310               * @param bool  $enabled        True if plugin update notifications are enabled, false otherwise.
1311               * @param array $update_results The results of plugins update tasks.
1312               */
1313              $notifications_enabled = apply_filters( 'auto_plugin_update_send_email', true, $update_results['plugin'] );
1314  
1315              if ( $notifications_enabled ) {
1316                  foreach ( $update_results['plugin'] as $update_result ) {
1317                      if ( true === $update_result->result ) {
1318                          $successful_updates['plugin'][] = $update_result;
1319                      } else {
1320                          $failed_updates['plugin'][] = $update_result;
1321                      }
1322                  }
1323              }
1324          }
1325  
1326          if ( ! empty( $update_results['theme'] ) ) {
1327              /**
1328               * Filters whether to send an email following an automatic background theme update.
1329               *
1330               * @since 5.5.0
1331               * @since 5.5.1 Added the `$update_results` parameter.
1332               *
1333               * @param bool  $enabled        True if theme update notifications are enabled, false otherwise.
1334               * @param array $update_results The results of theme update tasks.
1335               */
1336              $notifications_enabled = apply_filters( 'auto_theme_update_send_email', true, $update_results['theme'] );
1337  
1338              if ( $notifications_enabled ) {
1339                  foreach ( $update_results['theme'] as $update_result ) {
1340                      if ( true === $update_result->result ) {
1341                          $successful_updates['theme'][] = $update_result;
1342                      } else {
1343                          $failed_updates['theme'][] = $update_result;
1344                      }
1345                  }
1346              }
1347          }
1348  
1349          if ( empty( $successful_updates ) && empty( $failed_updates ) ) {
1350              return;
1351          }
1352  
1353          if ( empty( $failed_updates ) ) {
1354              $this->send_plugin_theme_email( 'success', $successful_updates, $failed_updates );
1355          } elseif ( empty( $successful_updates ) ) {
1356              $this->send_plugin_theme_email( 'fail', $successful_updates, $failed_updates );
1357          } else {
1358              $this->send_plugin_theme_email( 'mixed', $successful_updates, $failed_updates );
1359          }
1360      }
1361  
1362      /**
1363       * Sends an email upon the completion or failure of a plugin or theme background update.
1364       *
1365       * @since 5.5.0
1366       *
1367       * @param string $type               The type of email to send. Can be one of 'success', 'fail', 'mixed'.
1368       * @param array  $successful_updates A list of updates that succeeded.
1369       * @param array  $failed_updates     A list of updates that failed.
1370       *
1371       * @phpstan-param 'success'|'fail'|'mixed' $type
1372       * @phpstan-param array{ plugin?: list<Plugin_Update_Result>, theme?: list<Theme_Update_Result> } $successful_updates
1373       * @phpstan-param array{ plugin?: list<Plugin_Update_Result>, theme?: list<Theme_Update_Result> } $failed_updates
1374       */
1375  	protected function send_plugin_theme_email( $type, $successful_updates, $failed_updates ) {
1376          // No updates were attempted.
1377          if ( empty( $successful_updates ) && empty( $failed_updates ) ) {
1378              return;
1379          }
1380  
1381          $unique_failures     = false;
1382          $past_failure_emails = get_option( 'auto_plugin_theme_update_emails', array() );
1383  
1384          /*
1385           * When only failures have occurred, an email should only be sent if there are unique failures.
1386           * A failure is considered unique if an email has not been sent for an update attempt failure
1387           * to a plugin or theme with the same new_version.
1388           */
1389          if ( 'fail' === $type ) {
1390              foreach ( $failed_updates as $update_type => $failures ) {
1391                  foreach ( $failures as $failed_update ) {
1392                      if ( ! isset( $past_failure_emails[ $failed_update->item->{$update_type} ] ) ) {
1393                          $unique_failures = true;
1394                          continue;
1395                      }
1396  
1397                      // Check that the failure represents a new failure based on the new_version.
1398                      if ( version_compare( $past_failure_emails[ $failed_update->item->{$update_type} ], $failed_update->item->new_version, '<' ) ) {
1399                          $unique_failures = true;
1400                      }
1401                  }
1402              }
1403  
1404              if ( ! $unique_failures ) {
1405                  return;
1406              }
1407          }
1408  
1409          $admin_user = get_user_by( 'email', get_site_option( 'admin_email' ) );
1410  
1411          if ( $admin_user ) {
1412              $switched_locale = switch_to_user_locale( $admin_user->ID );
1413          } else {
1414              $switched_locale = switch_to_locale( get_locale() );
1415          }
1416  
1417          $body               = array();
1418          $successful_plugins = ( ! empty( $successful_updates['plugin'] ) );
1419          $successful_themes  = ( ! empty( $successful_updates['theme'] ) );
1420          $failed_plugins     = ( ! empty( $failed_updates['plugin'] ) );
1421          $failed_themes      = ( ! empty( $failed_updates['theme'] ) );
1422  
1423          switch ( $type ) {
1424              case 'success':
1425                  if ( $successful_plugins && $successful_themes ) {
1426                      /* translators: %s: Site title. */
1427                      $subject = __( '[%s] Some plugins and themes have automatically updated' );
1428                      $body[]  = sprintf(
1429                          /* translators: %s: Home URL. */
1430                          __( 'Howdy! Some plugins and themes have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
1431                          home_url()
1432                      );
1433                  } elseif ( $successful_plugins ) {
1434                      /* translators: %s: Site title. */
1435                      $subject = __( '[%s] Some plugins were automatically updated' );
1436                      $body[]  = sprintf(
1437                          /* translators: %s: Home URL. */
1438                          __( 'Howdy! Some plugins have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
1439                          home_url()
1440                      );
1441                  } else {
1442                      /* translators: %s: Site title. */
1443                      $subject = __( '[%s] Some themes were automatically updated' );
1444                      $body[]  = sprintf(
1445                          /* translators: %s: Home URL. */
1446                          __( 'Howdy! Some themes have automatically updated to their latest versions on your site at %s. No further action is needed on your part.' ),
1447                          home_url()
1448                      );
1449                  }
1450  
1451                  break;
1452              case 'fail':
1453              case 'mixed':
1454                  if ( $failed_plugins && $failed_themes ) {
1455                      /* translators: %s: Site title. */
1456                      $subject = __( '[%s] Some plugins and themes have failed to update' );
1457                      $body[]  = sprintf(
1458                          /* translators: %s: Home URL. */
1459                          __( 'Howdy! Plugins and themes failed to update on your site at %s.' ),
1460                          home_url()
1461                      );
1462                  } elseif ( $failed_plugins ) {
1463                      /* translators: %s: Site title. */
1464                      $subject = __( '[%s] Some plugins have failed to update' );
1465                      $body[]  = sprintf(
1466                          /* translators: %s: Home URL. */
1467                          __( 'Howdy! Plugins failed to update on your site at %s.' ),
1468                          home_url()
1469                      );
1470                  } else {
1471                      /* translators: %s: Site title. */
1472                      $subject = __( '[%s] Some themes have failed to update' );
1473                      $body[]  = sprintf(
1474                          /* translators: %s: Home URL. */
1475                          __( 'Howdy! Themes failed to update on your site at %s.' ),
1476                          home_url()
1477                      );
1478                  }
1479  
1480                  break;
1481          }
1482  
1483          if ( in_array( $type, array( 'fail', 'mixed' ), true ) ) {
1484              $body[] = "\n";
1485              $body[] = __( 'Please check your site now. It’s possible that everything is working. If there are updates available, you should update.' );
1486              $body[] = "\n";
1487  
1488              // List failed plugin updates.
1489              if ( ! empty( $failed_updates['plugin'] ) ) {
1490                  $body[] = __( 'The following plugins failed to update. If there was a fatal error in the update, the previously installed version has been restored.' );
1491  
1492                  foreach ( $failed_updates['plugin'] as $item ) {
1493                      $body_message = '';
1494                      $item_url     = '';
1495  
1496                      if ( ! empty( $item->item->url ) ) {
1497                          $item_url = ' : ' . esc_url( $item->item->url );
1498                      }
1499  
1500                      if ( $item->item->current_version ) {
1501                          $body_message .= sprintf(
1502                              /* translators: 1: Plugin name, 2: Current version number, 3: New version number, 4: Plugin URL. */
1503                              __( '- %1$s (from version %2$s to %3$s)%4$s' ),
1504                              html_entity_decode( $item->name ),
1505                              $item->item->current_version,
1506                              $item->item->new_version,
1507                              $item_url
1508                          );
1509                      } else {
1510                          $body_message .= sprintf(
1511                              /* translators: 1: Plugin name, 2: Version number, 3: Plugin URL. */
1512                              __( '- %1$s version %2$s%3$s' ),
1513                              html_entity_decode( $item->name ),
1514                              $item->item->new_version,
1515                              $item_url
1516                          );
1517                      }
1518  
1519                      $body[] = $body_message;
1520  
1521                      if ( isset( $item->result ) && is_wp_error( $item->result ) ) {
1522                          $fatal_error = $item->result->get_error_message( 'plugin_update_fatal_error' );
1523                          if ( '' !== $fatal_error ) {
1524                              $body[] = '  ' . $fatal_error;
1525                          }
1526                      }
1527  
1528                      $past_failure_emails[ $item->item->plugin ] = $item->item->new_version;
1529                  }
1530  
1531                  $body[] = "\n";
1532              }
1533  
1534              // List failed theme updates.
1535              if ( ! empty( $failed_updates['theme'] ) ) {
1536                  $body[] = __( 'These themes failed to update:' );
1537  
1538                  foreach ( $failed_updates['theme'] as $item ) {
1539                      if ( $item->item->current_version ) {
1540                          $body[] = sprintf(
1541                              /* translators: 1: Theme name, 2: Current version number, 3: New version number. */
1542                              __( '- %1$s (from version %2$s to %3$s)' ),
1543                              html_entity_decode( $item->name ),
1544                              $item->item->current_version,
1545                              $item->item->new_version
1546                          );
1547                      } else {
1548                          $body[] = sprintf(
1549                              /* translators: 1: Theme name, 2: Version number. */
1550                              __( '- %1$s version %2$s' ),
1551                              html_entity_decode( $item->name ),
1552                              $item->item->new_version
1553                          );
1554                      }
1555  
1556                      $past_failure_emails[ $item->item->theme ] = $item->item->new_version;
1557                  }
1558  
1559                  $body[] = "\n";
1560              }
1561          }
1562  
1563          // List successful updates.
1564          if ( in_array( $type, array( 'success', 'mixed' ), true ) ) {
1565              $body[] = "\n";
1566  
1567              // List successful plugin updates.
1568              if ( ! empty( $successful_updates['plugin'] ) ) {
1569                  $body[] = __( 'These plugins are now up to date:' );
1570  
1571                  foreach ( $successful_updates['plugin'] as $item ) {
1572                      $body_message = '';
1573                      $item_url     = '';
1574  
1575                      if ( ! empty( $item->item->url ) ) {
1576                          $item_url = ' : ' . esc_url( $item->item->url );
1577                      }
1578  
1579                      if ( $item->item->current_version ) {
1580                          $body_message .= sprintf(
1581                              /* translators: 1: Plugin name, 2: Current version number, 3: New version number, 4: Plugin URL. */
1582                              __( '- %1$s (from version %2$s to %3$s)%4$s' ),
1583                              html_entity_decode( $item->name ),
1584                              $item->item->current_version,
1585                              $item->item->new_version,
1586                              $item_url
1587                          );
1588                      } else {
1589                          $body_message .= sprintf(
1590                              /* translators: 1: Plugin name, 2: Version number, 3: Plugin URL. */
1591                              __( '- %1$s version %2$s%3$s' ),
1592                              html_entity_decode( $item->name ),
1593                              $item->item->new_version,
1594                              $item_url
1595                          );
1596                      }
1597                      $body[] = $body_message;
1598  
1599                      unset( $past_failure_emails[ $item->item->plugin ] );
1600                  }
1601  
1602                  $body[] = "\n";
1603              }
1604  
1605              // List successful theme updates.
1606              if ( ! empty( $successful_updates['theme'] ) ) {
1607                  $body[] = __( 'These themes are now up to date:' );
1608  
1609                  foreach ( $successful_updates['theme'] as $item ) {
1610                      if ( $item->item->current_version ) {
1611                          $body[] = sprintf(
1612                              /* translators: 1: Theme name, 2: Current version number, 3: New version number. */
1613                              __( '- %1$s (from version %2$s to %3$s)' ),
1614                              html_entity_decode( $item->name ),
1615                              $item->item->current_version,
1616                              $item->item->new_version
1617                          );
1618                      } else {
1619                          $body[] = sprintf(
1620                              /* translators: 1: Theme name, 2: Version number. */
1621                              __( '- %1$s version %2$s' ),
1622                              html_entity_decode( $item->name ),
1623                              $item->item->new_version
1624                          );
1625                      }
1626  
1627                      unset( $past_failure_emails[ $item->item->theme ] );
1628                  }
1629  
1630                  $body[] = "\n";
1631              }
1632          }
1633  
1634          if ( $failed_plugins ) {
1635              $body[] = sprintf(
1636                  /* translators: %s: Plugins screen URL. */
1637                  __( 'To manage plugins on your site, visit the Plugins page: %s' ),
1638                  admin_url( 'plugins.php' )
1639              );
1640              $body[] = "\n";
1641          }
1642  
1643          if ( $failed_themes ) {
1644              $body[] = sprintf(
1645                  /* translators: %s: Themes screen URL. */
1646                  __( 'To manage themes on your site, visit the Themes page: %s' ),
1647                  admin_url( 'themes.php' )
1648              );
1649              $body[] = "\n";
1650          }
1651  
1652          // Add a note about the support forums.
1653          $body[] = __( 'If you experience any issues or need support, the volunteers in the WordPress.org support forums may be able to help.' );
1654          $body[] = __( 'https://wordpress.org/support/forums/' );
1655          $body[] = "\n" . __( 'The WordPress Team' );
1656  
1657          if ( '' !== get_option( 'blogname' ) ) {
1658              $site_title = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
1659          } else {
1660              $site_title = parse_url( home_url(), PHP_URL_HOST );
1661          }
1662  
1663          $body    = implode( "\n", $body );
1664          $to      = get_site_option( 'admin_email' );
1665          $subject = sprintf( $subject, $site_title );
1666          $headers = '';
1667  
1668          $email = compact( 'to', 'subject', 'body', 'headers' );
1669  
1670          /**
1671           * Filters the email sent following an automatic background update for plugins and themes.
1672           *
1673           * @since 5.5.0
1674           *
1675           * @param array  $email {
1676           *     Array of email arguments that will be passed to wp_mail().
1677           *
1678           *     @type string $to      The email recipient. An array of emails
1679           *                           can be returned, as handled by wp_mail().
1680           *     @type string $subject The email's subject.
1681           *     @type string $body    The email message body.
1682           *     @type string $headers Any email headers, defaults to no headers.
1683           * }
1684           * @param string $type               The type of email being sent. Can be one of 'success', 'fail', 'mixed'.
1685           * @param array  $successful_updates A list of updates that succeeded.
1686           * @param array  $failed_updates     A list of updates that failed.
1687           */
1688          $email = apply_filters( 'auto_plugin_theme_update_email', $email, $type, $successful_updates, $failed_updates );
1689  
1690          $result = wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
1691  
1692          if ( $result ) {
1693              update_option( 'auto_plugin_theme_update_emails', $past_failure_emails );
1694          }
1695  
1696          if ( $switched_locale ) {
1697              restore_previous_locale();
1698          }
1699      }
1700  
1701      /**
1702       * Prepares and sends an email of a full log of background update results, useful for debugging and geekery.
1703       *
1704       * @since 3.7.0
1705       */
1706  	protected function send_debug_email() {
1707          $admin_user = get_user_by( 'email', get_site_option( 'admin_email' ) );
1708  
1709          if ( $admin_user ) {
1710              $switched_locale = switch_to_user_locale( $admin_user->ID );
1711          } else {
1712              $switched_locale = switch_to_locale( get_locale() );
1713          }
1714  
1715          $body     = array();
1716          $failures = 0;
1717  
1718          /* translators: %s: Network home URL. */
1719          $body[] = sprintf( __( 'WordPress site: %s' ), network_home_url( '/' ) );
1720  
1721          // Core.
1722          if ( isset( $this->update_results['core'] ) ) {
1723              $result = $this->update_results['core'][0];
1724  
1725              if ( $result->result && ! is_wp_error( $result->result ) ) {
1726                  /* translators: %s: WordPress version. */
1727                  $body[] = sprintf( __( 'SUCCESS: WordPress was successfully updated to %s' ), $result->name );
1728              } else {
1729                  /* translators: %s: WordPress version. */
1730                  $body[] = sprintf( __( 'FAILED: WordPress failed to update to %s' ), $result->name );
1731                  ++$failures;
1732              }
1733  
1734              $body[] = '';
1735          }
1736  
1737          // Plugins, Themes, Translations.
1738          foreach ( array( 'plugin', 'theme', 'translation' ) as $type ) {
1739              if ( ! isset( $this->update_results[ $type ] ) ) {
1740                  continue;
1741              }
1742  
1743              $success_items = wp_list_filter( $this->update_results[ $type ], array( 'result' => true ) );
1744  
1745              if ( $success_items ) {
1746                  $messages = array(
1747                      'plugin'      => __( 'The following plugins were successfully updated:' ),
1748                      'theme'       => __( 'The following themes were successfully updated:' ),
1749                      'translation' => __( 'The following translations were successfully updated:' ),
1750                  );
1751  
1752                  $body[] = $messages[ $type ];
1753                  foreach ( wp_list_pluck( $success_items, 'name' ) as $name ) {
1754                      /* translators: %s: Name of plugin / theme / translation. */
1755                      $body[] = ' * ' . sprintf( __( 'SUCCESS: %s' ), $name );
1756                  }
1757              }
1758  
1759              if ( $success_items !== $this->update_results[ $type ] ) {
1760                  // Failed updates.
1761                  $messages = array(
1762                      'plugin'      => __( 'The following plugins failed to update:' ),
1763                      'theme'       => __( 'The following themes failed to update:' ),
1764                      'translation' => __( 'The following translations failed to update:' ),
1765                  );
1766  
1767                  $body[] = $messages[ $type ];
1768  
1769                  foreach ( $this->update_results[ $type ] as $item ) {
1770                      if ( ! $item->result || is_wp_error( $item->result ) ) {
1771                          /* translators: %s: Name of plugin / theme / translation. */
1772                          $body[] = ' * ' . sprintf( __( 'FAILED: %s' ), $item->name );
1773                          ++$failures;
1774                      }
1775                  }
1776              }
1777  
1778              $body[] = '';
1779          }
1780  
1781          if ( '' !== get_bloginfo( 'name' ) ) {
1782              $site_title = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
1783          } else {
1784              $site_title = parse_url( home_url(), PHP_URL_HOST );
1785          }
1786  
1787          if ( $failures ) {
1788              $body[] = trim(
1789                  __(
1790                      "BETA TESTING?
1791  =============
1792  
1793  This debugging email is sent when you are using a development version of WordPress.
1794  
1795  If you think these failures might be due to a bug in WordPress, could you report it?
1796   * Open a thread in the support forums: https://wordpress.org/support/forum/alphabeta
1797   * Or, if you're comfortable writing a bug report: https://core.trac.wordpress.org/
1798  
1799  Thanks! -- The WordPress Team"
1800                  )
1801              );
1802              $body[] = '';
1803  
1804              /* translators: Background update failed notification email subject. %s: Site title. */
1805              $subject = sprintf( __( '[%s] Background Update Failed' ), $site_title );
1806          } else {
1807              /* translators: Background update finished notification email subject. %s: Site title. */
1808              $subject = sprintf( __( '[%s] Background Update Finished' ), $site_title );
1809          }
1810  
1811          $body[] = trim(
1812              __(
1813                  'UPDATE LOG
1814  =========='
1815              )
1816          );
1817          $body[] = '';
1818  
1819          foreach ( array( 'core', 'plugin', 'theme', 'translation' ) as $type ) {
1820              if ( ! isset( $this->update_results[ $type ] ) ) {
1821                  continue;
1822              }
1823  
1824              foreach ( $this->update_results[ $type ] as $update ) {
1825                  $body[] = $update->name;
1826                  $body[] = str_repeat( '-', strlen( $update->name ) );
1827  
1828                  foreach ( $update->messages as $message ) {
1829                      $body[] = '  ' . html_entity_decode( str_replace( '&#8230;', '...', $message ) );
1830                  }
1831  
1832                  if ( is_wp_error( $update->result ) ) {
1833                      $results = array( 'update' => $update->result );
1834  
1835                      // If we rolled back, we want to know an error that occurred then too.
1836                      if ( 'rollback_was_required' === $update->result->get_error_code() ) {
1837                          $results = (array) $update->result->get_error_data();
1838                      }
1839  
1840                      foreach ( $results as $result_type => $result ) {
1841                          if ( ! is_wp_error( $result ) ) {
1842                              continue;
1843                          }
1844  
1845                          if ( 'rollback' === $result_type ) {
1846                              /* translators: 1: Error code, 2: Error message. */
1847                              $body[] = '  ' . sprintf( __( 'Rollback Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
1848                          } else {
1849                              /* translators: 1: Error code, 2: Error message. */
1850                              $body[] = '  ' . sprintf( __( 'Error: [%1$s] %2$s' ), $result->get_error_code(), $result->get_error_message() );
1851                          }
1852  
1853                          if ( $result->get_error_data() ) {
1854                              $body[] = '         ' . implode( ', ', (array) $result->get_error_data() );
1855                          }
1856                      }
1857                  }
1858  
1859                  $body[] = '';
1860              }
1861          }
1862  
1863          $email = array(
1864              'to'      => get_site_option( 'admin_email' ),
1865              'subject' => $subject,
1866              'body'    => implode( "\n", $body ),
1867              'headers' => '',
1868          );
1869  
1870          /**
1871           * Filters the debug email that can be sent following an automatic
1872           * background core update.
1873           *
1874           * @since 3.8.0
1875           *
1876           * @param array $email {
1877           *     Array of email arguments that will be passed to wp_mail().
1878           *
1879           *     @type string $to      The email recipient. An array of emails
1880           *                           can be returned, as handled by wp_mail().
1881           *     @type string $subject Email subject.
1882           *     @type string $body    Email message body.
1883           *     @type string $headers Any email headers. Default empty.
1884           * }
1885           * @param int   $failures The number of failures encountered while upgrading.
1886           * @param mixed $results  The results of all attempted updates.
1887           */
1888          $email = apply_filters( 'automatic_updates_debug_email', $email, $failures, $this->update_results );
1889  
1890          wp_mail( $email['to'], wp_specialchars_decode( $email['subject'] ), $email['body'], $email['headers'] );
1891  
1892          if ( $switched_locale ) {
1893              restore_previous_locale();
1894          }
1895      }
1896  
1897      /**
1898       * Performs a loopback request to check for potential fatal errors.
1899       *
1900       * Fatal errors cannot be detected unless maintenance mode is enabled.
1901       *
1902       * @since 6.6.0
1903       * @since 7.2.0 Details of a detected fatal error are recorded for the update result.
1904       *
1905       * @global int $upgrading The Unix timestamp marking when upgrading WordPress began.
1906       *
1907       * @return bool Whether a fatal error was detected.
1908       */
1909  	protected function has_fatal_error() {
1910          global $upgrading;
1911  
1912          $this->fatal_error_message = null;
1913  
1914          $maintenance_file = ABSPATH . '.maintenance';
1915          if ( ! file_exists( $maintenance_file ) ) {
1916              return false;
1917          }
1918  
1919          require $maintenance_file;
1920          if ( ! is_int( $upgrading ) ) {
1921              return false;
1922          }
1923  
1924          $scrape_key   = md5( $upgrading );
1925          $scrape_nonce = (string) $upgrading;
1926          $transient    = 'scrape_key_' . $scrape_key;
1927          set_transient( $transient, $scrape_nonce, 30 );
1928  
1929          $cookies       = wp_unslash( $_COOKIE );
1930          $scrape_params = array(
1931              'wp_scrape_key'   => $scrape_key,
1932              'wp_scrape_nonce' => $scrape_nonce,
1933          );
1934          $headers       = array(
1935              'Cache-Control' => 'no-cache',
1936          );
1937  
1938          // Include Basic auth in the loopback request.
1939          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
1940              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
1941          }
1942  
1943          // Time to wait for loopback request to finish.
1944          $timeout = 50; // 50 seconds.
1945  
1946          $is_debug = WP_DEBUG && WP_DEBUG_LOG;
1947          if ( $is_debug ) {
1948              error_log( '    Scraping home page...' );
1949          }
1950  
1951          $needle_start = "###### wp_scraping_result_start:$scrape_key ######";
1952          $needle_end   = "###### wp_scraping_result_end:$scrape_key ######";
1953          $url          = add_query_arg( $scrape_params, home_url( '/' ) );
1954  
1955          /** This filter is documented in wp-includes/class-wp-http-streams.php */
1956          $sslverify = apply_filters( 'https_local_ssl_verify', false, $url );
1957          $response  = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
1958  
1959          if ( is_wp_error( $response ) ) {
1960              $this->fatal_error_message = sprintf(
1961                  /* translators: %s: Error message. */
1962                  __( 'The loopback request to check for fatal errors failed: %s' ),
1963                  $response->get_error_message()
1964              );
1965  
1966              if ( $is_debug ) {
1967                  error_log( 'Loopback request failed: ' . $response->get_error_message() );
1968              }
1969              return true;
1970          }
1971  
1972          // If this outputs `true` in the log, it means there were no fatal errors detected.
1973          if ( $is_debug ) {
1974              error_log( var_export( substr( $response['body'], strpos( $response['body'], '###### wp_scraping_result_start:' ) ), true ) );
1975          }
1976  
1977          $body                   = wp_remote_retrieve_body( $response );
1978          $scrape_result_position = strpos( $body, $needle_start );
1979          $result                 = null;
1980  
1981          if ( false !== $scrape_result_position ) {
1982              $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
1983              $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
1984              $result       = json_decode( trim( $error_output ), true );
1985          }
1986  
1987          if ( is_array( $result ) && isset( $result['type'] ) && ! empty( $result['message'] ) && is_string( $result['message'] ) ) {
1988              /*
1989               * Only the first line of the message is kept, as the message for an uncaught exception
1990               * continues with a stack trace, which can include the values of function arguments.
1991               */
1992              $this->fatal_error_message = sprintf(
1993                  'PHP Fatal error: %s in %s on line %d',
1994                  explode( "\n", $result['message'], 2 )[0],
1995                  isset( $result['file'] ) && is_string( $result['file'] ) ? $result['file'] : 'unknown',
1996                  isset( $result['line'] ) && is_numeric( $result['line'] ) ? (int) $result['line'] : 0
1997              );
1998          }
1999  
2000          delete_transient( $transient );
2001  
2002          // Only fatal errors will result in a 'type' key.
2003          return isset( $result['type'] );
2004      }
2005  }


Generated : Fri Nov 6 08:20:37 2026 Cross-referenced by PHPXref