[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Upgrade API: WP_Upgrader class
   4   *
   5   * Requires skin classes and WP_Upgrader subclasses for backward compatibility.
   6   *
   7   * @package WordPress
   8   * @subpackage Upgrader
   9   * @since 2.8.0
  10   */
  11  
  12  /** WP_Upgrader_Skin class */
  13  require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php';
  14  
  15  /** Plugin_Upgrader_Skin class */
  16  require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader-skin.php';
  17  
  18  /** Theme_Upgrader_Skin class */
  19  require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader-skin.php';
  20  
  21  /** Bulk_Upgrader_Skin class */
  22  require_once ABSPATH . 'wp-admin/includes/class-bulk-upgrader-skin.php';
  23  
  24  /** Bulk_Plugin_Upgrader_Skin class */
  25  require_once ABSPATH . 'wp-admin/includes/class-bulk-plugin-upgrader-skin.php';
  26  
  27  /** Bulk_Theme_Upgrader_Skin class */
  28  require_once ABSPATH . 'wp-admin/includes/class-bulk-theme-upgrader-skin.php';
  29  
  30  /** Plugin_Installer_Skin class */
  31  require_once ABSPATH . 'wp-admin/includes/class-plugin-installer-skin.php';
  32  
  33  /** Theme_Installer_Skin class */
  34  require_once ABSPATH . 'wp-admin/includes/class-theme-installer-skin.php';
  35  
  36  /** Language_Pack_Upgrader_Skin class */
  37  require_once ABSPATH . 'wp-admin/includes/class-language-pack-upgrader-skin.php';
  38  
  39  /** Automatic_Upgrader_Skin class */
  40  require_once ABSPATH . 'wp-admin/includes/class-automatic-upgrader-skin.php';
  41  
  42  /** WP_Ajax_Upgrader_Skin class */
  43  require_once ABSPATH . 'wp-admin/includes/class-wp-ajax-upgrader-skin.php';
  44  
  45  /**
  46   * Core class used for upgrading/installing a local set of files via
  47   * the Filesystem Abstraction classes from a Zip file.
  48   *
  49   * @since 2.8.0
  50   */
  51  class WP_Upgrader {
  52  
  53      /**
  54       * The error/notification strings used to update the user on the progress.
  55       *
  56       * @since 2.8.0
  57       * @var array $strings
  58       */
  59      public $strings = array();
  60  
  61      /**
  62       * The upgrader skin being used.
  63       *
  64       * @since 2.8.0
  65       * @var Automatic_Upgrader_Skin|WP_Upgrader_Skin $skin
  66       */
  67      public $skin = null;
  68  
  69      /**
  70       * The result of the installation.
  71       *
  72       * This is set by WP_Upgrader::install_package(), only when the package is installed
  73       * successfully. It will then be an array, unless a WP_Error is returned by the
  74       * {@see 'upgrader_post_install'} filter. In that case, the WP_Error will be assigned to
  75       * it.
  76       *
  77       * @since 2.8.0
  78       *
  79       * @var array|WP_Error $result {
  80       *     @type string $source             The full path to the source the files were installed from.
  81       *     @type string $source_files       List of all the files in the source directory.
  82       *     @type string $destination        The full path to the installation destination folder.
  83       *     @type string $destination_name   The name of the destination folder, or empty if `$destination`
  84       *                                      and `$local_destination` are the same.
  85       *     @type string $local_destination  The full local path to the destination folder. This is usually
  86       *                                      the same as `$destination`.
  87       *     @type string $remote_destination The full remote path to the destination folder
  88       *                                      (i.e., from `$wp_filesystem`).
  89       *     @type bool   $clear_destination  Whether the destination folder was cleared.
  90       * }
  91       */
  92      public $result = array();
  93  
  94      /**
  95       * The total number of updates being performed.
  96       *
  97       * Set by the bulk update methods.
  98       *
  99       * @since 3.0.0
 100       * @var int $update_count
 101       */
 102      public $update_count = 0;
 103  
 104      /**
 105       * The current update if multiple updates are being performed.
 106       *
 107       * Used by the bulk update methods, and incremented for each update.
 108       *
 109       * @since 3.0.0
 110       * @var int
 111       */
 112      public $update_current = 0;
 113  
 114      /**
 115       * Construct the upgrader with a skin.
 116       *
 117       * @since 2.8.0
 118       *
 119       * @param WP_Upgrader_Skin $skin The upgrader skin to use. Default is a WP_Upgrader_Skin
 120       *                               instance.
 121       */
 122  	public function __construct( $skin = null ) {
 123          if ( null === $skin ) {
 124              $this->skin = new WP_Upgrader_Skin();
 125          } else {
 126              $this->skin = $skin;
 127          }
 128      }
 129  
 130      /**
 131       * Initialize the upgrader.
 132       *
 133       * This will set the relationship between the skin being used and this upgrader,
 134       * and also add the generic strings to `WP_Upgrader::$strings`.
 135       *
 136       * Additionally, it will schedule a weekly task to clean up the temp-backup directory.
 137       *
 138       * @since 2.8.0
 139       * @since 5.9.0 Added the `schedule_temp_backup_cleanup()` task.
 140       */
 141  	public function init() {
 142          $this->skin->set_upgrader( $this );
 143          $this->generic_strings();
 144          $this->schedule_temp_backup_cleanup();
 145      }
 146  
 147      /**
 148       * Schedule cleanup of the temp-backup directory.
 149       *
 150       * @since 5.9.0
 151       */
 152  	protected function schedule_temp_backup_cleanup() {
 153          wp_schedule_event( time(), 'weekly', 'delete_temp_updater_backups' );
 154          add_action( 'delete_temp_updater_backups', array( $this, 'delete_all_temp_backups' ) );
 155      }
 156  
 157      /**
 158       * Add the generic strings to WP_Upgrader::$strings.
 159       *
 160       * @since 2.8.0
 161       */
 162  	public function generic_strings() {
 163          $this->strings['bad_request']       = __( 'Invalid data provided.' );
 164          $this->strings['fs_unavailable']    = __( 'Could not access filesystem.' );
 165          $this->strings['fs_error']          = __( 'Filesystem error.' );
 166          $this->strings['fs_no_root_dir']    = __( 'Unable to locate WordPress root directory.' );
 167          $this->strings['fs_no_content_dir'] = __( 'Unable to locate WordPress content directory (wp-content).' );
 168          $this->strings['fs_no_plugins_dir'] = __( 'Unable to locate WordPress plugin directory.' );
 169          $this->strings['fs_no_themes_dir']  = __( 'Unable to locate WordPress theme directory.' );
 170          /* translators: %s: Directory name. */
 171          $this->strings['fs_no_folder'] = __( 'Unable to locate needed folder (%s).' );
 172  
 173          $this->strings['download_failed']      = __( 'Download failed.' );
 174          $this->strings['installing_package']   = __( 'Installing the latest version&#8230;' );
 175          $this->strings['no_files']             = __( 'The package contains no files.' );
 176          $this->strings['folder_exists']        = __( 'Destination folder already exists.' );
 177          $this->strings['mkdir_failed']         = __( 'Could not create directory.' );
 178          $this->strings['incompatible_archive'] = __( 'The package could not be installed.' );
 179          $this->strings['files_not_writable']   = __( 'The update cannot be installed because we will be unable to copy some files. This is usually due to inconsistent file permissions.' );
 180  
 181          $this->strings['maintenance_start'] = __( 'Enabling Maintenance mode&#8230;' );
 182          $this->strings['maintenance_end']   = __( 'Disabling Maintenance mode&#8230;' );
 183  
 184          /* translators: %s: temp-backup */
 185          $this->strings['temp_backup_mkdir_failed'] = sprintf( __( 'Could not create the %s directory.' ), 'temp-backup' );
 186          /* translators: %s: temp-backup */
 187          $this->strings['temp_backup_move_failed']    = sprintf( __( 'Could not move old version to the %s directory.' ), 'temp-backup' );
 188          $this->strings['temp_backup_restore_failed'] = __( 'Could not restore original version.' );
 189  
 190      }
 191  
 192      /**
 193       * Connect to the filesystem.
 194       *
 195       * @since 2.8.0
 196       *
 197       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
 198       *
 199       * @param string[] $directories                  Optional. Array of directories. If any of these do
 200       *                                               not exist, a WP_Error object will be returned.
 201       *                                               Default empty array.
 202       * @param bool     $allow_relaxed_file_ownership Whether to allow relaxed file ownership.
 203       *                                               Default false.
 204       * @return bool|WP_Error True if able to connect, false or a WP_Error otherwise.
 205       */
 206  	public function fs_connect( $directories = array(), $allow_relaxed_file_ownership = false ) {
 207          global $wp_filesystem;
 208  
 209          $credentials = $this->skin->request_filesystem_credentials( false, $directories[0], $allow_relaxed_file_ownership );
 210          if ( false === $credentials ) {
 211              return false;
 212          }
 213  
 214          if ( ! WP_Filesystem( $credentials, $directories[0], $allow_relaxed_file_ownership ) ) {
 215              $error = true;
 216              if ( is_object( $wp_filesystem ) && $wp_filesystem->errors->has_errors() ) {
 217                  $error = $wp_filesystem->errors;
 218              }
 219              // Failed to connect. Error and request again.
 220              $this->skin->request_filesystem_credentials( $error, $directories[0], $allow_relaxed_file_ownership );
 221              return false;
 222          }
 223  
 224          if ( ! is_object( $wp_filesystem ) ) {
 225              return new WP_Error( 'fs_unavailable', $this->strings['fs_unavailable'] );
 226          }
 227  
 228          if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
 229              return new WP_Error( 'fs_error', $this->strings['fs_error'], $wp_filesystem->errors );
 230          }
 231  
 232          foreach ( (array) $directories as $dir ) {
 233              switch ( $dir ) {
 234                  case ABSPATH:
 235                      if ( ! $wp_filesystem->abspath() ) {
 236                          return new WP_Error( 'fs_no_root_dir', $this->strings['fs_no_root_dir'] );
 237                      }
 238                      break;
 239                  case WP_CONTENT_DIR:
 240                      if ( ! $wp_filesystem->wp_content_dir() ) {
 241                          return new WP_Error( 'fs_no_content_dir', $this->strings['fs_no_content_dir'] );
 242                      }
 243                      break;
 244                  case WP_PLUGIN_DIR:
 245                      if ( ! $wp_filesystem->wp_plugins_dir() ) {
 246                          return new WP_Error( 'fs_no_plugins_dir', $this->strings['fs_no_plugins_dir'] );
 247                      }
 248                      break;
 249                  case get_theme_root():
 250                      if ( ! $wp_filesystem->wp_themes_dir() ) {
 251                          return new WP_Error( 'fs_no_themes_dir', $this->strings['fs_no_themes_dir'] );
 252                      }
 253                      break;
 254                  default:
 255                      if ( ! $wp_filesystem->find_folder( $dir ) ) {
 256                          return new WP_Error( 'fs_no_folder', sprintf( $this->strings['fs_no_folder'], esc_html( basename( $dir ) ) ) );
 257                      }
 258                      break;
 259              }
 260          }
 261          return true;
 262      }
 263  
 264      /**
 265       * Download a package.
 266       *
 267       * @since 2.8.0
 268       * @since 5.2.0 Added the `$check_signatures` parameter.
 269       * @since 5.5.0 Added the `$hook_extra` parameter.
 270       *
 271       * @param string $package          The URI of the package. If this is the full path to an
 272       *                                 existing local file, it will be returned untouched.
 273       * @param bool   $check_signatures Whether to validate file signatures. Default false.
 274       * @param array  $hook_extra       Extra arguments to pass to the filter hooks. Default empty array.
 275       * @return string|WP_Error The full path to the downloaded package file, or a WP_Error object.
 276       */
 277  	public function download_package( $package, $check_signatures = false, $hook_extra = array() ) {
 278          /**
 279           * Filters whether to return the package.
 280           *
 281           * @since 3.7.0
 282           * @since 5.5.0 Added the `$hook_extra` parameter.
 283           *
 284           * @param bool        $reply      Whether to bail without returning the package.
 285           *                                Default false.
 286           * @param string      $package    The package file name.
 287           * @param WP_Upgrader $upgrader   The WP_Upgrader instance.
 288           * @param array       $hook_extra Extra arguments passed to hooked filters.
 289           */
 290          $reply = apply_filters( 'upgrader_pre_download', false, $package, $this, $hook_extra );
 291          if ( false !== $reply ) {
 292              return $reply;
 293          }
 294  
 295          if ( ! preg_match( '!^(http|https|ftp)://!i', $package ) && file_exists( $package ) ) { // Local file or remote?
 296              return $package; // Must be a local file.
 297          }
 298  
 299          if ( empty( $package ) ) {
 300              return new WP_Error( 'no_package', $this->strings['no_package'] );
 301          }
 302  
 303          $this->skin->feedback( 'downloading_package', $package );
 304  
 305          $download_file = download_url( $package, 300, $check_signatures );
 306  
 307          if ( is_wp_error( $download_file ) && ! $download_file->get_error_data( 'softfail-filename' ) ) {
 308              return new WP_Error( 'download_failed', $this->strings['download_failed'], $download_file->get_error_message() );
 309          }
 310  
 311          return $download_file;
 312      }
 313  
 314      /**
 315       * Unpack a compressed package file.
 316       *
 317       * @since 2.8.0
 318       *
 319       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
 320       *
 321       * @param string $package        Full path to the package file.
 322       * @param bool   $delete_package Optional. Whether to delete the package file after attempting
 323       *                               to unpack it. Default true.
 324       * @return string|WP_Error The path to the unpacked contents, or a WP_Error on failure.
 325       */
 326  	public function unpack_package( $package, $delete_package = true ) {
 327          global $wp_filesystem;
 328  
 329          $this->skin->feedback( 'unpack_package' );
 330  
 331          $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/';
 332  
 333          // Clean up contents of upgrade directory beforehand.
 334          $upgrade_files = $wp_filesystem->dirlist( $upgrade_folder );
 335          if ( ! empty( $upgrade_files ) ) {
 336              foreach ( $upgrade_files as $file ) {
 337                  if ( 'temp-backup' === $file['name'] ) {
 338                      continue;
 339                  }
 340                  $wp_filesystem->delete( $upgrade_folder . $file['name'], true );
 341              }
 342          }
 343  
 344          // We need a working directory - strip off any .tmp or .zip suffixes.
 345          $working_dir = $upgrade_folder . basename( basename( $package, '.tmp' ), '.zip' );
 346  
 347          // Clean up working directory.
 348          if ( $wp_filesystem->is_dir( $working_dir ) ) {
 349              $wp_filesystem->delete( $working_dir, true );
 350          }
 351  
 352          // Unzip package to working directory.
 353          $result = unzip_file( $package, $working_dir );
 354  
 355          // Once extracted, delete the package if required.
 356          if ( $delete_package ) {
 357              unlink( $package );
 358          }
 359  
 360          if ( is_wp_error( $result ) ) {
 361              $wp_filesystem->delete( $working_dir, true );
 362              if ( 'incompatible_archive' === $result->get_error_code() ) {
 363                  return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() );
 364              }
 365              return $result;
 366          }
 367  
 368          return $working_dir;
 369      }
 370  
 371      /**
 372       * Flatten the results of WP_Filesystem_Base::dirlist() for iterating over.
 373       *
 374       * @since 4.9.0
 375       * @access protected
 376       *
 377       * @param array  $nested_files Array of files as returned by WP_Filesystem_Base::dirlist().
 378       * @param string $path         Relative path to prepend to child nodes. Optional.
 379       * @return array A flattened array of the $nested_files specified.
 380       */
 381  	protected function flatten_dirlist( $nested_files, $path = '' ) {
 382          $files = array();
 383  
 384          foreach ( $nested_files as $name => $details ) {
 385              $files[ $path . $name ] = $details;
 386  
 387              // Append children recursively.
 388              if ( ! empty( $details['files'] ) ) {
 389                  $children = $this->flatten_dirlist( $details['files'], $path . $name . '/' );
 390  
 391                  // Merge keeping possible numeric keys, which array_merge() will reindex from 0..n.
 392                  $files = $files + $children;
 393              }
 394          }
 395  
 396          return $files;
 397      }
 398  
 399      /**
 400       * Clears the directory where this item is going to be installed into.
 401       *
 402       * @since 4.3.0
 403       *
 404       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
 405       *
 406       * @param string $remote_destination The location on the remote filesystem to be cleared.
 407       * @return bool|WP_Error True upon success, WP_Error on failure.
 408       */
 409  	public function clear_destination( $remote_destination ) {
 410          global $wp_filesystem;
 411  
 412          $files = $wp_filesystem->dirlist( $remote_destination, true, true );
 413  
 414          // False indicates that the $remote_destination doesn't exist.
 415          if ( false === $files ) {
 416              return true;
 417          }
 418  
 419          // Flatten the file list to iterate over.
 420          $files = $this->flatten_dirlist( $files );
 421  
 422          // Check all files are writable before attempting to clear the destination.
 423          $unwritable_files = array();
 424  
 425          // Check writability.
 426          foreach ( $files as $filename => $file_details ) {
 427              if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
 428                  // Attempt to alter permissions to allow writes and try again.
 429                  $wp_filesystem->chmod( $remote_destination . $filename, ( 'd' === $file_details['type'] ? FS_CHMOD_DIR : FS_CHMOD_FILE ) );
 430                  if ( ! $wp_filesystem->is_writable( $remote_destination . $filename ) ) {
 431                      $unwritable_files[] = $filename;
 432                  }
 433              }
 434          }
 435  
 436          if ( ! empty( $unwritable_files ) ) {
 437              return new WP_Error( 'files_not_writable', $this->strings['files_not_writable'], implode( ', ', $unwritable_files ) );
 438          }
 439  
 440          if ( ! $wp_filesystem->delete( $remote_destination, true ) ) {
 441              return new WP_Error( 'remove_old_failed', $this->strings['remove_old_failed'] );
 442          }
 443  
 444          return true;
 445      }
 446  
 447      /**
 448       * Install a package.
 449       *
 450       * Copies the contents of a package from a source directory, and installs them in
 451       * a destination directory. Optionally removes the source. It can also optionally
 452       * clear out the destination folder if it already exists.
 453       *
 454       * @since 2.8.0
 455       *
 456       * @global WP_Filesystem_Base $wp_filesystem        WordPress filesystem subclass.
 457       * @global array              $wp_theme_directories
 458       *
 459       * @param array|string $args {
 460       *     Optional. Array or string of arguments for installing a package. Default empty array.
 461       *
 462       *     @type string $source                      Required path to the package source. Default empty.
 463       *     @type string $destination                 Required path to a folder to install the package in.
 464       *                                               Default empty.
 465       *     @type bool   $clear_destination           Whether to delete any files already in the destination
 466       *                                               folder. Default false.
 467       *     @type bool   $clear_working               Whether to delete the files from the working directory
 468       *                                               after copying them to the destination. Default false.
 469       *     @type bool   $abort_if_destination_exists Whether to abort the installation if
 470       *                                               the destination folder already exists. Default true.
 471       *     @type array  $hook_extra                  Extra arguments to pass to the filter hooks called by
 472       *                                               WP_Upgrader::install_package(). Default empty array.
 473       * }
 474       *
 475       * @return array|WP_Error The result (also stored in `WP_Upgrader::$result`), or a WP_Error on failure.
 476       */
 477  	public function install_package( $args = array() ) {
 478          global $wp_filesystem, $wp_theme_directories;
 479  
 480          $defaults = array(
 481              'source'                      => '', // Please always pass this.
 482              'destination'                 => '', // ...and this.
 483              'clear_destination'           => false,
 484              'clear_working'               => false,
 485              'abort_if_destination_exists' => true,
 486              'hook_extra'                  => array(),
 487          );
 488  
 489          $args = wp_parse_args( $args, $defaults );
 490  
 491          // These were previously extract()'d.
 492          $source            = $args['source'];
 493          $destination       = $args['destination'];
 494          $clear_destination = $args['clear_destination'];
 495  
 496          set_time_limit( 300 );
 497  
 498          if ( empty( $source ) || empty( $destination ) ) {
 499              return new WP_Error( 'bad_request', $this->strings['bad_request'] );
 500          }
 501          $this->skin->feedback( 'installing_package' );
 502  
 503          /**
 504           * Filters the install response before the installation has started.
 505           *
 506           * Returning a value that could be evaluated as a `WP_Error` will effectively
 507           * short-circuit the installation, returning that value instead.
 508           *
 509           * @since 2.8.0
 510           *
 511           * @param bool|WP_Error $response   Response.
 512           * @param array         $hook_extra Extra arguments passed to hooked filters.
 513           */
 514          $res = apply_filters( 'upgrader_pre_install', true, $args['hook_extra'] );
 515  
 516          if ( is_wp_error( $res ) ) {
 517              return $res;
 518          }
 519  
 520          if ( ! empty( $args['hook_extra']['temp_backup'] ) ) {
 521              $temp_backup = $this->move_to_temp_backup_dir( $args['hook_extra']['temp_backup'] );
 522              if ( is_wp_error( $temp_backup ) ) {
 523                  return $temp_backup;
 524              }
 525          }
 526  
 527          // Retain the original source and destinations.
 528          $remote_source     = $args['source'];
 529          $local_destination = $destination;
 530  
 531          $source_files       = array_keys( $wp_filesystem->dirlist( $remote_source ) );
 532          $remote_destination = $wp_filesystem->find_folder( $local_destination );
 533  
 534          // Locate which directory to copy to the new folder. This is based on the actual folder holding the files.
 535          if ( 1 === count( $source_files ) && $wp_filesystem->is_dir( trailingslashit( $args['source'] ) . $source_files[0] . '/' ) ) {
 536              // Only one folder? Then we want its contents.
 537              $source = trailingslashit( $args['source'] ) . trailingslashit( $source_files[0] );
 538          } elseif ( 0 === count( $source_files ) ) {
 539              // There are no files?
 540              return new WP_Error( 'incompatible_archive_empty', $this->strings['incompatible_archive'], $this->strings['no_files'] );
 541          } else {
 542              // It's only a single file, the upgrader will use the folder name of this file as the destination folder.
 543              // Folder name is based on zip filename.
 544              $source = trailingslashit( $args['source'] );
 545          }
 546  
 547          /**
 548           * Filters the source file location for the upgrade package.
 549           *
 550           * @since 2.8.0
 551           * @since 4.4.0 The $hook_extra parameter became available.
 552           *
 553           * @param string      $source        File source location.
 554           * @param string      $remote_source Remote file source location.
 555           * @param WP_Upgrader $upgrader      WP_Upgrader instance.
 556           * @param array       $hook_extra    Extra arguments passed to hooked filters.
 557           */
 558          $source = apply_filters( 'upgrader_source_selection', $source, $remote_source, $this, $args['hook_extra'] );
 559  
 560          if ( is_wp_error( $source ) ) {
 561              return $source;
 562          }
 563  
 564          // Has the source location changed? If so, we need a new source_files list.
 565          if ( $source !== $remote_source ) {
 566              $source_files = array_keys( $wp_filesystem->dirlist( $source ) );
 567          }
 568  
 569          /*
 570           * Protection against deleting files in any important base directories.
 571           * Theme_Upgrader & Plugin_Upgrader also trigger this, as they pass the
 572           * destination directory (WP_PLUGIN_DIR / wp-content/themes) intending
 573           * to copy the directory into the directory, whilst they pass the source
 574           * as the actual files to copy.
 575           */
 576          $protected_directories = array( ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' );
 577  
 578          if ( is_array( $wp_theme_directories ) ) {
 579              $protected_directories = array_merge( $protected_directories, $wp_theme_directories );
 580          }
 581  
 582          if ( in_array( $destination, $protected_directories, true ) ) {
 583              $remote_destination = trailingslashit( $remote_destination ) . trailingslashit( basename( $source ) );
 584              $destination        = trailingslashit( $destination ) . trailingslashit( basename( $source ) );
 585          }
 586  
 587          if ( $clear_destination ) {
 588              // We're going to clear the destination if there's something there.
 589              $this->skin->feedback( 'remove_old' );
 590  
 591              $removed = $this->clear_destination( $remote_destination );
 592  
 593              /**
 594               * Filters whether the upgrader cleared the destination.
 595               *
 596               * @since 2.8.0
 597               *
 598               * @param true|WP_Error $removed            Whether the destination was cleared.
 599               *                                          True upon success, WP_Error on failure.
 600               * @param string        $local_destination  The local package destination.
 601               * @param string        $remote_destination The remote package destination.
 602               * @param array         $hook_extra         Extra arguments passed to hooked filters.
 603               */
 604              $removed = apply_filters( 'upgrader_clear_destination', $removed, $local_destination, $remote_destination, $args['hook_extra'] );
 605  
 606              if ( is_wp_error( $removed ) ) {
 607                  return $removed;
 608              }
 609          } elseif ( $args['abort_if_destination_exists'] && $wp_filesystem->exists( $remote_destination ) ) {
 610              // If we're not clearing the destination folder and something exists there already, bail.
 611              // But first check to see if there are actually any files in the folder.
 612              $_files = $wp_filesystem->dirlist( $remote_destination );
 613              if ( ! empty( $_files ) ) {
 614                  $wp_filesystem->delete( $remote_source, true ); // Clear out the source files.
 615                  return new WP_Error( 'folder_exists', $this->strings['folder_exists'], $remote_destination );
 616              }
 617          }
 618  
 619          // Create destination if needed.
 620          if ( ! $wp_filesystem->exists( $remote_destination ) ) {
 621              if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) {
 622                  return new WP_Error( 'mkdir_failed_destination', $this->strings['mkdir_failed'], $remote_destination );
 623              }
 624          }
 625  
 626          // Move new version of item into place.
 627          $result = move_dir( $source, $remote_destination );
 628          if ( is_wp_error( $result ) ) {
 629              if ( $args['clear_working'] ) {
 630                  $wp_filesystem->delete( $remote_source, true );
 631              }
 632              return $result;
 633          }
 634  
 635          // Clear the working folder?
 636          if ( $args['clear_working'] ) {
 637              $wp_filesystem->delete( $remote_source, true );
 638          }
 639  
 640          $destination_name = basename( str_replace( $local_destination, '', $destination ) );
 641          if ( '.' === $destination_name ) {
 642              $destination_name = '';
 643          }
 644  
 645          $this->result = compact( 'source', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination' );
 646  
 647          /**
 648           * Filters the installation response after the installation has finished.
 649           *
 650           * @since 2.8.0
 651           *
 652           * @param bool  $response   Installation response.
 653           * @param array $hook_extra Extra arguments passed to hooked filters.
 654           * @param array $result     Installation result data.
 655           */
 656          $res = apply_filters( 'upgrader_post_install', true, $args['hook_extra'], $this->result );
 657  
 658          if ( is_wp_error( $res ) ) {
 659              $this->result = $res;
 660              return $res;
 661          }
 662  
 663          // Bombard the calling function will all the info which we've just used.
 664          return $this->result;
 665      }
 666  
 667      /**
 668       * Run an upgrade/installation.
 669       *
 670       * Attempts to download the package (if it is not a local file), unpack it, and
 671       * install it in the destination folder.
 672       *
 673       * @since 2.8.0
 674       *
 675       * @param array $options {
 676       *     Array or string of arguments for upgrading/installing a package.
 677       *
 678       *     @type string $package                     The full path or URI of the package to install.
 679       *                                               Default empty.
 680       *     @type string $destination                 The full path to the destination folder.
 681       *                                               Default empty.
 682       *     @type bool   $clear_destination           Whether to delete any files already in the
 683       *                                               destination folder. Default false.
 684       *     @type bool   $clear_working               Whether to delete the files from the working
 685       *                                               directory after copying them to the destination.
 686       *                                               Default false.
 687       *     @type bool   $abort_if_destination_exists Whether to abort the installation if the destination
 688       *                                               folder already exists. When true, `$clear_destination`
 689       *                                               should be false. Default true.
 690       *     @type bool   $is_multi                    Whether this run is one of multiple upgrade/installation
 691       *                                               actions being performed in bulk. When true, the skin
 692       *                                               WP_Upgrader::header() and WP_Upgrader::footer()
 693       *                                               aren't called. Default false.
 694       *     @type array  $hook_extra                  Extra arguments to pass to the filter hooks called by
 695       *                                               WP_Upgrader::run().
 696       * }
 697       * @return array|false|WP_Error The result from self::install_package() on success, otherwise a WP_Error,
 698       *                              or false if unable to connect to the filesystem.
 699       */
 700  	public function run( $options ) {
 701  
 702          $defaults = array(
 703              'package'                     => '', // Please always pass this.
 704              'destination'                 => '', // ...and this.
 705              'clear_destination'           => false,
 706              'abort_if_destination_exists' => true, // Abort if the destination directory exists. Pass clear_destination as false please.
 707              'clear_working'               => true,
 708              'is_multi'                    => false,
 709              'hook_extra'                  => array(), // Pass any extra $hook_extra args here, this will be passed to any hooked filters.
 710          );
 711  
 712          $options = wp_parse_args( $options, $defaults );
 713  
 714          /**
 715           * Filters the package options before running an update.
 716           *
 717           * See also {@see 'upgrader_process_complete'}.
 718           *
 719           * @since 4.3.0
 720           *
 721           * @param array $options {
 722           *     Options used by the upgrader.
 723           *
 724           *     @type string $package                     Package for update.
 725           *     @type string $destination                 Update location.
 726           *     @type bool   $clear_destination           Clear the destination resource.
 727           *     @type bool   $clear_working               Clear the working resource.
 728           *     @type bool   $abort_if_destination_exists Abort if the Destination directory exists.
 729           *     @type bool   $is_multi                    Whether the upgrader is running multiple times.
 730           *     @type array  $hook_extra {
 731           *         Extra hook arguments.
 732           *
 733           *         @type string $action               Type of action. Default 'update'.
 734           *         @type string $type                 Type of update process. Accepts 'plugin', 'theme', or 'core'.
 735           *         @type bool   $bulk                 Whether the update process is a bulk update. Default true.
 736           *         @type string $plugin               Path to the plugin file relative to the plugins directory.
 737           *         @type string $theme                The stylesheet or template name of the theme.
 738           *         @type string $language_update_type The language pack update type. Accepts 'plugin', 'theme',
 739           *                                            or 'core'.
 740           *         @type object $language_update      The language pack update offer.
 741           *     }
 742           * }
 743           */
 744          $options = apply_filters( 'upgrader_package_options', $options );
 745  
 746          if ( ! $options['is_multi'] ) { // Call $this->header separately if running multiple times.
 747              $this->skin->header();
 748          }
 749  
 750          // Connect to the filesystem first.
 751          $res = $this->fs_connect( array( WP_CONTENT_DIR, $options['destination'] ) );
 752          // Mainly for non-connected filesystem.
 753          if ( ! $res ) {
 754              if ( ! $options['is_multi'] ) {
 755                  $this->skin->footer();
 756              }
 757              return false;
 758          }
 759  
 760          $this->skin->before();
 761  
 762          if ( is_wp_error( $res ) ) {
 763              $this->skin->error( $res );
 764              $this->skin->after();
 765              if ( ! $options['is_multi'] ) {
 766                  $this->skin->footer();
 767              }
 768              return $res;
 769          }
 770  
 771          /*
 772           * Download the package. Note: If the package is the full path
 773           * to an existing local file, it will be returned untouched.
 774           */
 775          $download = $this->download_package( $options['package'], true, $options['hook_extra'] );
 776  
 777          // Allow for signature soft-fail.
 778          // WARNING: This may be removed in the future.
 779          if ( is_wp_error( $download ) && $download->get_error_data( 'softfail-filename' ) ) {
 780  
 781              // Don't output the 'no signature could be found' failure message for now.
 782              if ( 'signature_verification_no_signature' !== $download->get_error_code() || WP_DEBUG ) {
 783                  // Output the failure error as a normal feedback, and not as an error.
 784                  $this->skin->feedback( $download->get_error_message() );
 785  
 786                  // Report this failure back to WordPress.org for debugging purposes.
 787                  wp_version_check(
 788                      array(
 789                          'signature_failure_code' => $download->get_error_code(),
 790                          'signature_failure_data' => $download->get_error_data(),
 791                      )
 792                  );
 793              }
 794  
 795              // Pretend this error didn't happen.
 796              $download = $download->get_error_data( 'softfail-filename' );
 797          }
 798  
 799          if ( is_wp_error( $download ) ) {
 800              $this->skin->error( $download );
 801              $this->skin->after();
 802              if ( ! $options['is_multi'] ) {
 803                  $this->skin->footer();
 804              }
 805              return $download;
 806          }
 807  
 808          $delete_package = ( $download !== $options['package'] ); // Do not delete a "local" file.
 809  
 810          // Unzips the file into a temporary directory.
 811          $working_dir = $this->unpack_package( $download, $delete_package );
 812          if ( is_wp_error( $working_dir ) ) {
 813              $this->skin->error( $working_dir );
 814              $this->skin->after();
 815              if ( ! $options['is_multi'] ) {
 816                  $this->skin->footer();
 817              }
 818              return $working_dir;
 819          }
 820  
 821          // With the given options, this installs it to the destination directory.
 822          $result = $this->install_package(
 823              array(
 824                  'source'                      => $working_dir,
 825                  'destination'                 => $options['destination'],
 826                  'clear_destination'           => $options['clear_destination'],
 827                  'abort_if_destination_exists' => $options['abort_if_destination_exists'],
 828                  'clear_working'               => $options['clear_working'],
 829                  'hook_extra'                  => $options['hook_extra'],
 830              )
 831          );
 832  
 833          /**
 834           * Filters the result of WP_Upgrader::install_package().
 835           *
 836           * @since 5.7.0
 837           *
 838           * @param array|WP_Error $result     Result from WP_Upgrader::install_package().
 839           * @param array          $hook_extra Extra arguments passed to hooked filters.
 840           */
 841          $result = apply_filters( 'upgrader_install_package_result', $result, $options['hook_extra'] );
 842  
 843          $this->skin->set_result( $result );
 844          if ( is_wp_error( $result ) ) {
 845              if ( ! empty( $options['hook_extra']['temp_backup'] ) ) {
 846                  /*
 847                   * Restore the backup on shutdown.
 848                   * Actions running on `shutdown` are immune to PHP timeouts,
 849                   * so in case the failure was due to a PHP timeout,
 850                   * we'll still be able to properly restore the previous version.
 851                   */
 852                  add_action(
 853                      'shutdown',
 854                      function() use ( $options ) {
 855                          $this->restore_temp_backup( $options['hook_extra']['temp_backup'] );
 856                      }
 857                  );
 858              }
 859              $this->skin->error( $result );
 860  
 861              if ( ! method_exists( $this->skin, 'hide_process_failed' ) || ! $this->skin->hide_process_failed( $result ) ) {
 862                  $this->skin->feedback( 'process_failed' );
 863              }
 864          } else {
 865              // Installation succeeded.
 866              $this->skin->feedback( 'process_success' );
 867          }
 868  
 869          $this->skin->after();
 870  
 871          // Clean up the backup kept in the temp-backup directory.
 872          if ( ! empty( $options['hook_extra']['temp_backup'] ) ) {
 873              // Delete the backup on `shutdown` to avoid a PHP timeout.
 874              add_action(
 875                  'shutdown',
 876                  function() use ( $options ) {
 877                      $this->delete_temp_backup( $options['hook_extra']['temp_backup'] );
 878                  }
 879              );
 880          }
 881  
 882          if ( ! $options['is_multi'] ) {
 883  
 884              /**
 885               * Fires when the upgrader process is complete.
 886               *
 887               * See also {@see 'upgrader_package_options'}.
 888               *
 889               * @since 3.6.0
 890               * @since 3.7.0 Added to WP_Upgrader::run().
 891               * @since 4.6.0 `$translations` was added as a possible argument to `$hook_extra`.
 892               *
 893               * @param WP_Upgrader $upgrader   WP_Upgrader instance. In other contexts this might be a
 894               *                                Theme_Upgrader, Plugin_Upgrader, Core_Upgrade, or Language_Pack_Upgrader instance.
 895               * @param array       $hook_extra {
 896               *     Array of bulk item update data.
 897               *
 898               *     @type string $action       Type of action. Default 'update'.
 899               *     @type string $type         Type of update process. Accepts 'plugin', 'theme', 'translation', or 'core'.
 900               *     @type bool   $bulk         Whether the update process is a bulk update. Default true.
 901               *     @type array  $plugins      Array of the basename paths of the plugins' main files.
 902               *     @type array  $themes       The theme slugs.
 903               *     @type array  $translations {
 904               *         Array of translations update data.
 905               *
 906               *         @type string $language The locale the translation is for.
 907               *         @type string $type     Type of translation. Accepts 'plugin', 'theme', or 'core'.
 908               *         @type string $slug     Text domain the translation is for. The slug of a theme/plugin or
 909               *                                'default' for core translations.
 910               *         @type string $version  The version of a theme, plugin, or core.
 911               *     }
 912               * }
 913               */
 914              do_action( 'upgrader_process_complete', $this, $options['hook_extra'] );
 915  
 916              $this->skin->footer();
 917          }
 918  
 919          return $result;
 920      }
 921  
 922      /**
 923       * Toggle maintenance mode for the site.
 924       *
 925       * Creates/deletes the maintenance file to enable/disable maintenance mode.
 926       *
 927       * @since 2.8.0
 928       *
 929       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
 930       *
 931       * @param bool $enable True to enable maintenance mode, false to disable.
 932       */
 933  	public function maintenance_mode( $enable = false ) {
 934          global $wp_filesystem;
 935          $file = $wp_filesystem->abspath() . '.maintenance';
 936          if ( $enable ) {
 937              $this->skin->feedback( 'maintenance_start' );
 938              // Create maintenance file to signal that we are upgrading.
 939              $maintenance_string = '<?php $upgrading = ' . time() . '; ?>';
 940              $wp_filesystem->delete( $file );
 941              $wp_filesystem->put_contents( $file, $maintenance_string, FS_CHMOD_FILE );
 942          } elseif ( ! $enable && $wp_filesystem->exists( $file ) ) {
 943              $this->skin->feedback( 'maintenance_end' );
 944              $wp_filesystem->delete( $file );
 945          }
 946      }
 947  
 948      /**
 949       * Creates a lock using WordPress options.
 950       *
 951       * @since 4.5.0
 952       *
 953       * @param string $lock_name       The name of this unique lock.
 954       * @param int    $release_timeout Optional. The duration in seconds to respect an existing lock.
 955       *                                Default: 1 hour.
 956       * @return bool False if a lock couldn't be created or if the lock is still valid. True otherwise.
 957       */
 958  	public static function create_lock( $lock_name, $release_timeout = null ) {
 959          global $wpdb;
 960          if ( ! $release_timeout ) {
 961              $release_timeout = HOUR_IN_SECONDS;
 962          }
 963          $lock_option = $lock_name . '.lock';
 964  
 965          // Try to lock.
 966          $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_option, time() ) );
 967  
 968          if ( ! $lock_result ) {
 969              $lock_result = get_option( $lock_option );
 970  
 971              // If a lock couldn't be created, and there isn't a lock, bail.
 972              if ( ! $lock_result ) {
 973                  return false;
 974              }
 975  
 976              // Check to see if the lock is still valid. If it is, bail.
 977              if ( $lock_result > ( time() - $release_timeout ) ) {
 978                  return false;
 979              }
 980  
 981              // There must exist an expired lock, clear it and re-gain it.
 982              WP_Upgrader::release_lock( $lock_name );
 983  
 984              return WP_Upgrader::create_lock( $lock_name, $release_timeout );
 985          }
 986  
 987          // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
 988          update_option( $lock_option, time() );
 989  
 990          return true;
 991      }
 992  
 993      /**
 994       * Releases an upgrader lock.
 995       *
 996       * @since 4.5.0
 997       *
 998       * @see WP_Upgrader::create_lock()
 999       *
1000       * @param string $lock_name The name of this unique lock.
1001       * @return bool True if the lock was successfully released. False on failure.
1002       */
1003  	public static function release_lock( $lock_name ) {
1004          return delete_option( $lock_name . '.lock' );
1005      }
1006  
1007      /**
1008       * Moves the plugin/theme being updated into a temp-backup directory.
1009       *
1010       * @since 5.9.0
1011       *
1012       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1013       *
1014       * @param array $args Array of data for the temp-backup. Must include a slug, the source, and directory.
1015       * @return bool|WP_Error
1016       */
1017  	public function move_to_temp_backup_dir( $args ) {
1018          global $wp_filesystem;
1019  
1020          if ( empty( $args['slug'] ) || empty( $args['src'] ) || empty( $args['dir'] ) ) {
1021              return false;
1022          }
1023  
1024          $dest_dir = $wp_filesystem->wp_content_dir() . 'upgrade/temp-backup/';
1025          // Create the temp-backup directory if it doesn't exist.
1026          if ( (
1027                  ! $wp_filesystem->is_dir( $dest_dir )
1028                  && ! $wp_filesystem->mkdir( $dest_dir )
1029              ) || (
1030                  ! $wp_filesystem->is_dir( $dest_dir . $args['dir'] . '/' )
1031                  && ! $wp_filesystem->mkdir( $dest_dir . $args['dir'] . '/' )
1032              )
1033          ) {
1034              return new WP_Error( 'fs_temp_backup_mkdir', $this->strings['temp_backup_mkdir_failed'] );
1035          }
1036  
1037          $src  = trailingslashit( $args['src'] ) . $args['slug'];
1038          $dest = $dest_dir . $args['dir'] . '/' . $args['slug'];
1039  
1040          // Delete the temp-backup directory if it already exists.
1041          if ( $wp_filesystem->is_dir( $dest ) ) {
1042              $wp_filesystem->delete( $dest, true );
1043          }
1044  
1045          // Move to the temp-backup directory.
1046          if ( ! $wp_filesystem->move( $src, $dest, true ) ) {
1047              return new WP_Error( 'fs_temp_backup_move', $this->strings['temp_backup_move_failed'] );
1048          }
1049  
1050          return true;
1051      }
1052  
1053      /**
1054       * Restores the plugin/theme from the temp-backup directory.
1055       *
1056       * @since 5.9.0
1057       *
1058       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1059       *
1060       * @param array $args Array of data for the temp-backup. Must include a slug, the source, and directory.
1061       * @return bool|WP_Error
1062       */
1063  	public function restore_temp_backup( $args ) {
1064          global $wp_filesystem;
1065  
1066          if ( empty( $args['slug'] ) || empty( $args['src'] ) || empty( $args['dir'] ) ) {
1067              return false;
1068          }
1069  
1070          $src  = $wp_filesystem->wp_content_dir() . 'upgrade/temp-backup/' . $args['dir'] . '/' . $args['slug'];
1071          $dest = trailingslashit( $args['src'] ) . $args['slug'];
1072  
1073          if ( $wp_filesystem->is_dir( $src ) ) {
1074              // Cleanup.
1075              if ( $wp_filesystem->is_dir( $dest ) && ! $wp_filesystem->delete( $dest, true ) ) {
1076                  return new WP_Error( 'fs_temp_backup_delete', $this->strings['temp_backup_restore_failed'] );
1077              }
1078  
1079              // Move it.
1080              if ( ! $wp_filesystem->move( $src, $dest, true ) ) {
1081                  return new WP_Error( 'fs_temp_backup_delete', $this->strings['temp_backup_restore_failed'] );
1082              }
1083          }
1084  
1085          return true;
1086      }
1087  
1088      /**
1089       * Deletes a temp-backup.
1090       *
1091       * @since 5.9.0
1092       *
1093       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1094       *
1095       * @param array $args Array of data for the temp-backup. Must include a slug, the source, and directory.
1096       * @return bool
1097       */
1098  	public function delete_temp_backup( $args ) {
1099          global $wp_filesystem;
1100  
1101          if ( empty( $args['slug'] ) || empty( $args['dir'] ) ) {
1102              return false;
1103          }
1104  
1105          return $wp_filesystem->delete(
1106              $wp_filesystem->wp_content_dir() . "upgrade/temp-backup/{$args['dir']}/{$args['slug']}",
1107              true
1108          );
1109      }
1110  
1111      /**
1112       * Deletes all contents of the temp-backup directory.
1113       *
1114       * @since 5.9.0
1115       *
1116       * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1117       */
1118  	public function delete_all_temp_backups() {
1119          /*
1120           * Check if there's a lock, or if currently performing an Ajax request,
1121           * in which case there's a chance we're doing an update.
1122           * Reschedule for an hour from now and exit early.
1123           */
1124          if ( get_option( 'core_updater.lock' ) || get_option( 'auto_updater.lock' ) || wp_doing_ajax() ) {
1125              wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'delete_temp_updater_backups' );
1126              return;
1127          }
1128  
1129          add_action(
1130              'shutdown',
1131              /*
1132               * This action runs on shutdown to make sure there's no plugin updates currently running.
1133               * Using a closure in this case is OK since the action can be removed by removing the parent hook.
1134               */
1135              function() {
1136                  global $wp_filesystem;
1137  
1138                  if ( ! $wp_filesystem ) {
1139                      include_once ABSPATH . '/wp-admin/includes/file.php';
1140                      WP_Filesystem();
1141                  }
1142  
1143                  $dirlist = $wp_filesystem->dirlist( $wp_filesystem->wp_content_dir() . 'upgrade/temp-backup/' );
1144  
1145                  foreach ( array_keys( $dirlist ) as $dir ) {
1146                      if ( '.' === $dir || '..' === $dir ) {
1147                          continue;
1148                      }
1149  
1150                      $wp_filesystem->delete( $wp_filesystem->wp_content_dir() . 'upgrade/temp-backup/' . $dir, true );
1151                  }
1152              }
1153          );
1154      }
1155  }
1156  
1157  /** Plugin_Upgrader class */
1158  require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';
1159  
1160  /** Theme_Upgrader class */
1161  require_once ABSPATH . 'wp-admin/includes/class-theme-upgrader.php';
1162  
1163  /** Language_Pack_Upgrader class */
1164  require_once ABSPATH . 'wp-admin/includes/class-language-pack-upgrader.php';
1165  
1166  /** Core_Upgrader class */
1167  require_once ABSPATH . 'wp-admin/includes/class-core-upgrader.php';
1168  
1169  /** File_Upload_Upgrader class */
1170  require_once ABSPATH . 'wp-admin/includes/class-file-upload-upgrader.php';
1171  
1172  /** WP_Automatic_Updater class */
1173  require_once ABSPATH . 'wp-admin/includes/class-wp-automatic-updater.php';


Generated: Tue Oct 19 01:00:04 2021 Cross-referenced by PHPXref 0.7.1