[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-admin/includes/ -> file.php (source)

   1  <?php
   2  /**
   3   * Filesystem API: Top-level functionality
   4   *
   5   * Functions for reading, writing, modifying, and deleting files on the file system.
   6   * Includes functionality for theme-specific files as well as operations for uploading,
   7   * archiving, and rendering output when necessary.
   8   *
   9   * @package WordPress
  10   * @subpackage Filesystem
  11   * @since 2.3.0
  12   */
  13  
  14  /** The descriptions for theme files. */
  15  $wp_file_descriptions = array(
  16      'functions.php'         => __( 'Theme Functions' ),
  17      'header.php'            => __( 'Theme Header' ),
  18      'footer.php'            => __( 'Theme Footer' ),
  19      'sidebar.php'           => __( 'Sidebar' ),
  20      'comments.php'          => __( 'Comments' ),
  21      'searchform.php'        => __( 'Search Form' ),
  22      '404.php'               => __( '404 Template' ),
  23      'link.php'              => __( 'Links Template' ),
  24      'theme.json'            => __( 'Theme Styles & Block Settings' ),
  25      // Archives.
  26      'index.php'             => __( 'Main Index Template' ),
  27      'archive.php'           => __( 'Archives' ),
  28      'author.php'            => __( 'Author Template' ),
  29      'taxonomy.php'          => __( 'Taxonomy Template' ),
  30      'category.php'          => __( 'Category Template' ),
  31      'tag.php'               => __( 'Tag Template' ),
  32      'home.php'              => __( 'Posts Page' ),
  33      'search.php'            => __( 'Search Results' ),
  34      'date.php'              => __( 'Date Template' ),
  35      // Content.
  36      'singular.php'          => __( 'Singular Template' ),
  37      'single.php'            => __( 'Single Post' ),
  38      'page.php'              => __( 'Single Page' ),
  39      'front-page.php'        => __( 'Homepage' ),
  40      'privacy-policy.php'    => __( 'Privacy Policy Page' ),
  41      // Attachments.
  42      'attachment.php'        => __( 'Attachment Template' ),
  43      'image.php'             => __( 'Image Attachment Template' ),
  44      'video.php'             => __( 'Video Attachment Template' ),
  45      'audio.php'             => __( 'Audio Attachment Template' ),
  46      'application.php'       => __( 'Application Attachment Template' ),
  47      // Embeds.
  48      'embed.php'             => __( 'Embed Template' ),
  49      'embed-404.php'         => __( 'Embed 404 Template' ),
  50      'embed-content.php'     => __( 'Embed Content Template' ),
  51      'header-embed.php'      => __( 'Embed Header Template' ),
  52      'footer-embed.php'      => __( 'Embed Footer Template' ),
  53      // Stylesheets.
  54      'style.css'             => __( 'Stylesheet' ),
  55      'editor-style.css'      => __( 'Visual Editor Stylesheet' ),
  56      'editor-style-rtl.css'  => __( 'Visual Editor RTL Stylesheet' ),
  57      'rtl.css'               => __( 'RTL Stylesheet' ),
  58      // Other.
  59      'my-hacks.php'          => __( 'my-hacks.php (legacy hacks support)' ),
  60      '.htaccess'             => __( '.htaccess (for rewrite rules )' ),
  61      // Deprecated files.
  62      'wp-layout.css'         => __( 'Stylesheet' ),
  63      'wp-comments.php'       => __( 'Comments Template' ),
  64      'wp-comments-popup.php' => __( 'Popup Comments Template' ),
  65      'comments-popup.php'    => __( 'Popup Comments' ),
  66  );
  67  
  68  /**
  69   * Gets the description for standard WordPress theme files.
  70   *
  71   * @since 1.5.0
  72   *
  73   * @global array $wp_file_descriptions Theme file descriptions.
  74   * @global array $allowed_files        List of allowed files.
  75   *
  76   * @param string $file Filesystem path or filename.
  77   * @return string Description of file from $wp_file_descriptions or basename of $file if description doesn't exist.
  78   *                Appends 'Page Template' to basename of $file if the file is a page template.
  79   */
  80  function get_file_description( $file ) {
  81      global $wp_file_descriptions, $allowed_files;
  82  
  83      $dirname   = pathinfo( $file, PATHINFO_DIRNAME );
  84      $file_path = $allowed_files[ $file ];
  85  
  86      if ( isset( $wp_file_descriptions[ basename( $file ) ] ) && '.' === $dirname ) {
  87          return $wp_file_descriptions[ basename( $file ) ];
  88      } elseif ( file_exists( $file_path ) && is_file( $file_path ) ) {
  89          $template_data = implode( '', file( $file_path ) );
  90  
  91          if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) ) {
  92              /* translators: %s: Template name. */
  93              return sprintf( __( '%s Page Template' ), _cleanup_header_comment( $name[1] ) );
  94          }
  95      }
  96  
  97      return trim( basename( $file ) );
  98  }
  99  
 100  /**
 101   * Gets the absolute filesystem path to the root of the WordPress installation.
 102   *
 103   * @since 1.5.0
 104   *
 105   * @return string Full filesystem path to the root of the WordPress installation.
 106   */
 107  function get_home_path() {
 108      $home    = set_url_scheme( get_option( 'home' ), 'http' );
 109      $siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
 110  
 111      if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) {
 112          $wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
 113          $pos                 = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );
 114          $home_path           = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
 115          $home_path           = trailingslashit( $home_path );
 116      } else {
 117          $home_path = ABSPATH;
 118      }
 119  
 120      return str_replace( '\\', '/', $home_path );
 121  }
 122  
 123  /**
 124   * Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep.
 125   *
 126   * The depth of the recursiveness can be controlled by the $levels param.
 127   *
 128   * @since 2.6.0
 129   * @since 4.9.0 Added the `$exclusions` parameter.
 130   * @since 6.3.0 Added the `$include_hidden` parameter.
 131   *
 132   * @param string   $folder         Optional. Full path to folder. Default empty.
 133   * @param int      $levels         Optional. Levels of folders to follow, Default 100 (PHP Loop limit).
 134   * @param string[] $exclusions     Optional. List of folders and files to skip.
 135   * @param bool     $include_hidden Optional. Whether to include details of hidden ("." prefixed) files.
 136   *                                 Default false.
 137   * @return string[]|false Array of files on success, false on failure.
 138   */
 139  function list_files( $folder = '', $levels = 100, $exclusions = array(), $include_hidden = false ) {
 140      if ( empty( $folder ) ) {
 141          return false;
 142      }
 143  
 144      $folder = trailingslashit( $folder );
 145  
 146      if ( ! $levels ) {
 147          return false;
 148      }
 149  
 150      $files = array();
 151  
 152      $dir = @opendir( $folder );
 153  
 154      if ( $dir ) {
 155          while ( ( $file = readdir( $dir ) ) !== false ) {
 156              // Skip current and parent folder links.
 157              if ( in_array( $file, array( '.', '..' ), true ) ) {
 158                  continue;
 159              }
 160  
 161              // Skip hidden and excluded files.
 162              if ( ( ! $include_hidden && '.' === $file[0] ) || in_array( $file, $exclusions, true ) ) {
 163                  continue;
 164              }
 165  
 166              if ( is_dir( $folder . $file ) ) {
 167                  $files2 = list_files( $folder . $file, $levels - 1, array(), $include_hidden );
 168                  if ( $files2 ) {
 169                      $files = array_merge( $files, $files2 );
 170                  } else {
 171                      $files[] = $folder . $file . '/';
 172                  }
 173              } else {
 174                  $files[] = $folder . $file;
 175              }
 176          }
 177  
 178          closedir( $dir );
 179      }
 180  
 181      return $files;
 182  }
 183  
 184  /**
 185   * Gets the list of file extensions that are editable in plugins.
 186   *
 187   * @since 4.9.0
 188   *
 189   * @param string $plugin Path to the plugin file relative to the plugins directory.
 190   * @return string[] Array of editable file extensions.
 191   */
 192  function wp_get_plugin_file_editable_extensions( $plugin ) {
 193  
 194      $default_types = array(
 195          'bash',
 196          'conf',
 197          'css',
 198          'diff',
 199          'htm',
 200          'html',
 201          'http',
 202          'inc',
 203          'include',
 204          'js',
 205          'mjs',
 206          'json',
 207          'jsx',
 208          'less',
 209          'md',
 210          'patch',
 211          'php',
 212          'php3',
 213          'php4',
 214          'php5',
 215          'php7',
 216          'phps',
 217          'phtml',
 218          'sass',
 219          'scss',
 220          'sh',
 221          'sql',
 222          'svg',
 223          'text',
 224          'txt',
 225          'xml',
 226          'yaml',
 227          'yml',
 228      );
 229  
 230      /**
 231       * Filters the list of file types allowed for editing in the plugin file editor.
 232       *
 233       * @since 2.8.0
 234       * @since 4.9.0 Added the `$plugin` parameter.
 235       *
 236       * @param string[] $default_types An array of editable plugin file extensions.
 237       * @param string   $plugin        Path to the plugin file relative to the plugins directory.
 238       */
 239      $file_types = (array) apply_filters( 'editable_extensions', $default_types, $plugin );
 240  
 241      return $file_types;
 242  }
 243  
 244  /**
 245   * Gets the list of file extensions that are editable for a given theme.
 246   *
 247   * @since 4.9.0
 248   *
 249   * @param WP_Theme $theme Theme object.
 250   * @return string[] Array of editable file extensions.
 251   */
 252  function wp_get_theme_file_editable_extensions( $theme ) {
 253  
 254      $default_types = array(
 255          'bash',
 256          'conf',
 257          'css',
 258          'diff',
 259          'htm',
 260          'html',
 261          'http',
 262          'inc',
 263          'include',
 264          'js',
 265          'mjs',
 266          'json',
 267          'jsx',
 268          'less',
 269          'md',
 270          'patch',
 271          'php',
 272          'php3',
 273          'php4',
 274          'php5',
 275          'php7',
 276          'phps',
 277          'phtml',
 278          'sass',
 279          'scss',
 280          'sh',
 281          'sql',
 282          'svg',
 283          'text',
 284          'txt',
 285          'xml',
 286          'yaml',
 287          'yml',
 288      );
 289  
 290      /**
 291       * Filters the list of file types allowed for editing in the theme file editor.
 292       *
 293       * @since 4.4.0
 294       *
 295       * @param string[] $default_types An array of editable theme file extensions.
 296       * @param WP_Theme $theme         The active theme object.
 297       */
 298      $file_types = apply_filters( 'wp_theme_editor_filetypes', $default_types, $theme );
 299  
 300      // Ensure that default types are still there.
 301      return array_unique( array_merge( $file_types, $default_types ) );
 302  }
 303  
 304  /**
 305   * Prints file editor templates (for plugins and themes).
 306   *
 307   * @since 4.9.0
 308   */
 309  function wp_print_file_editor_templates() {
 310      ?>
 311      <script type="text/html" id="tmpl-wp-file-editor-notice">
 312          <div class="notice inline notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.classes || '' }}">
 313              <# if ( 'php_error' === data.code ) { #>
 314                  <p>
 315                      <?php
 316                      printf(
 317                          /* translators: 1: Line number, 2: File path. */
 318                          __( 'Your PHP code changes were not applied due to an error on line %1$s of file %2$s. Please fix and try saving again.' ),
 319                          '{{ data.line }}',
 320                          '{{ data.file }}'
 321                      );
 322                      ?>
 323                  </p>
 324                  <pre>{{ data.message }}</pre>
 325              <# } else if ( 'file_not_writable' === data.code ) { #>
 326                  <p>
 327                      <?php
 328                      printf(
 329                          /* translators: %s: Documentation URL. */
 330                          __( 'You need to make this file writable before you can save your changes. See <a href="%s">Changing File Permissions</a> for more information.' ),
 331                          __( 'https://developer.wordpress.org/advanced-administration/server/file-permissions/' )
 332                      );
 333                      ?>
 334                  </p>
 335              <# } else { #>
 336                  <p>{{ data.message || data.code }}</p>
 337  
 338                  <# if ( 'lint_errors' === data.code ) { #>
 339                      <p>
 340                          <# var elementId = 'el-' + String( Math.random() ); #>
 341                          <input id="{{ elementId }}"  type="checkbox">
 342                          <label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label>
 343                      </p>
 344                  <# } #>
 345              <# } #>
 346              <# if ( data.dismissible ) { #>
 347                  <button type="button" class="notice-dismiss"><span class="screen-reader-text">
 348                      <?php
 349                      /* translators: Hidden accessibility text. */
 350                      _e( 'Dismiss' );
 351                      ?>
 352                  </span></button>
 353              <# } #>
 354          </div>
 355      </script>
 356      <?php
 357  }
 358  
 359  /**
 360   * Attempts to edit a file for a theme or plugin.
 361   *
 362   * When editing a PHP file, loopback requests will be made to the admin and the homepage
 363   * to attempt to see if there is a fatal error introduced. If so, the PHP change will be
 364   * reverted.
 365   *
 366   * @since 4.9.0
 367   *
 368   * @param string[] $args {
 369   *     Args. Note that all of the arg values are already unslashed. They are, however,
 370   *     coming straight from `$_POST` and are not validated or sanitized in any way.
 371   *
 372   *     @type string $file       Relative path to file.
 373   *     @type string $plugin     Path to the plugin file relative to the plugins directory.
 374   *     @type string $theme      Theme being edited.
 375   *     @type string $newcontent New content for the file.
 376   *     @type string $nonce      Nonce.
 377   * }
 378   * @return true|WP_Error True on success or `WP_Error` on failure.
 379   */
 380  function wp_edit_theme_plugin_file( $args ) {
 381      if ( empty( $args['file'] ) ) {
 382          return new WP_Error( 'missing_file' );
 383      }
 384  
 385      if ( 0 !== validate_file( $args['file'] ) ) {
 386          return new WP_Error( 'bad_file' );
 387      }
 388  
 389      if ( ! isset( $args['newcontent'] ) ) {
 390          return new WP_Error( 'missing_content' );
 391      }
 392  
 393      if ( ! isset( $args['nonce'] ) ) {
 394          return new WP_Error( 'missing_nonce' );
 395      }
 396  
 397      $file    = $args['file'];
 398      $content = $args['newcontent'];
 399  
 400      $plugin     = null;
 401      $stylesheet = null;
 402      $theme      = null;
 403      $real_file  = null;
 404  
 405      if ( ! empty( $args['plugin'] ) ) {
 406          $plugin = $args['plugin'];
 407  
 408          if ( ! current_user_can( 'edit_plugins' ) ) {
 409              return new WP_Error( 'unauthorized', __( 'Sorry, you are not allowed to edit plugins for this site.' ) );
 410          }
 411  
 412          if ( ! wp_verify_nonce( $args['nonce'], 'edit-plugin_' . $file ) ) {
 413              return new WP_Error( 'nonce_failure' );
 414          }
 415  
 416          if ( ! array_key_exists( $plugin, get_plugins() ) ) {
 417              return new WP_Error( 'invalid_plugin' );
 418          }
 419  
 420          if ( 0 !== validate_file( $file, get_plugin_files( $plugin ) ) ) {
 421              return new WP_Error( 'bad_plugin_file_path', __( 'Sorry, that file cannot be edited.' ) );
 422          }
 423  
 424          $editable_extensions = wp_get_plugin_file_editable_extensions( $plugin );
 425  
 426          $real_file = WP_PLUGIN_DIR . '/' . $file;
 427  
 428          $is_active = in_array(
 429              $plugin,
 430              (array) get_option( 'active_plugins', array() ),
 431              true
 432          );
 433  
 434      } elseif ( ! empty( $args['theme'] ) ) {
 435          $stylesheet = $args['theme'];
 436  
 437          if ( 0 !== validate_file( $stylesheet ) ) {
 438              return new WP_Error( 'bad_theme_path' );
 439          }
 440  
 441          if ( ! current_user_can( 'edit_themes' ) ) {
 442              return new WP_Error( 'unauthorized', __( 'Sorry, you are not allowed to edit templates for this site.' ) );
 443          }
 444  
 445          $theme = wp_get_theme( $stylesheet );
 446          if ( ! $theme->exists() ) {
 447              return new WP_Error( 'non_existent_theme', __( 'The requested theme does not exist.' ) );
 448          }
 449  
 450          if ( ! wp_verify_nonce( $args['nonce'], 'edit-theme_' . $stylesheet . '_' . $file ) ) {
 451              return new WP_Error( 'nonce_failure' );
 452          }
 453  
 454          if ( $theme->errors() && 'theme_no_stylesheet' === $theme->errors()->get_error_code() ) {
 455              return new WP_Error(
 456                  'theme_no_stylesheet',
 457                  __( 'The requested theme does not exist.' ) . ' ' . $theme->errors()->get_error_message()
 458              );
 459          }
 460  
 461          $editable_extensions = wp_get_theme_file_editable_extensions( $theme );
 462  
 463          $allowed_files = array();
 464          foreach ( $editable_extensions as $type ) {
 465              switch ( $type ) {
 466                  case 'php':
 467                      $allowed_files = array_merge( $allowed_files, $theme->get_files( 'php', -1 ) );
 468                      break;
 469                  case 'css':
 470                      $style_files                = $theme->get_files( 'css', -1 );
 471                      $allowed_files['style.css'] = $style_files['style.css'];
 472                      $allowed_files              = array_merge( $allowed_files, $style_files );
 473                      break;
 474                  default:
 475                      $allowed_files = array_merge( $allowed_files, $theme->get_files( $type, -1 ) );
 476                      break;
 477              }
 478          }
 479  
 480          // Compare based on relative paths.
 481          if ( 0 !== validate_file( $file, array_keys( $allowed_files ) ) ) {
 482              return new WP_Error( 'disallowed_theme_file', __( 'Sorry, that file cannot be edited.' ) );
 483          }
 484  
 485          $real_file = $theme->get_stylesheet_directory() . '/' . $file;
 486  
 487          $is_active = ( get_stylesheet() === $stylesheet || get_template() === $stylesheet );
 488  
 489      } else {
 490          return new WP_Error( 'missing_theme_or_plugin' );
 491      }
 492  
 493      // Ensure file is real.
 494      if ( ! is_file( $real_file ) ) {
 495          return new WP_Error( 'file_does_not_exist', __( 'File does not exist! Please double check the name and try again.' ) );
 496      }
 497  
 498      // Ensure file extension is allowed.
 499      $extension = null;
 500      if ( preg_match( '/\.([^.]+)$/', $real_file, $matches ) ) {
 501          $extension = strtolower( $matches[1] );
 502          if ( ! in_array( $extension, $editable_extensions, true ) ) {
 503              return new WP_Error( 'illegal_file_type', __( 'Files of this type are not editable.' ) );
 504          }
 505      }
 506  
 507      $previous_content = file_get_contents( $real_file );
 508  
 509      if ( ! is_writable( $real_file ) ) {
 510          return new WP_Error( 'file_not_writable' );
 511      }
 512  
 513      $f = fopen( $real_file, 'w+' );
 514  
 515      if ( false === $f ) {
 516          return new WP_Error( 'file_not_writable' );
 517      }
 518  
 519      $written = fwrite( $f, $content );
 520      fclose( $f );
 521  
 522      if ( false === $written ) {
 523          return new WP_Error( 'unable_to_write', __( 'Unable to write to file.' ) );
 524      }
 525  
 526      wp_opcache_invalidate( $real_file, true );
 527  
 528      if ( $is_active && 'php' === $extension ) {
 529  
 530          $scrape_key   = md5( rand() );
 531          $transient    = 'scrape_key_' . $scrape_key;
 532          $scrape_nonce = (string) rand();
 533          // It shouldn't take more than 60 seconds to make the two loopback requests.
 534          set_transient( $transient, $scrape_nonce, 60 );
 535  
 536          $cookies       = wp_unslash( $_COOKIE );
 537          $scrape_params = array(
 538              'wp_scrape_key'   => $scrape_key,
 539              'wp_scrape_nonce' => $scrape_nonce,
 540          );
 541          $headers       = array(
 542              'Cache-Control' => 'no-cache',
 543          );
 544  
 545          // Include Basic auth in loopback requests.
 546          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
 547              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
 548          }
 549  
 550          // Make sure PHP process doesn't die before loopback requests complete.
 551          if ( function_exists( 'set_time_limit' ) ) {
 552              set_time_limit( 5 * MINUTE_IN_SECONDS );
 553          }
 554  
 555          // Time to wait for loopback requests to finish.
 556          $timeout = 100; // 100 seconds.
 557  
 558          $needle_start = "###### wp_scraping_result_start:$scrape_key ######";
 559          $needle_end   = "###### wp_scraping_result_end:$scrape_key ######";
 560  
 561          // Attempt loopback request to editor to see if user just whitescreened themselves.
 562          if ( $plugin ) {
 563              $url = add_query_arg( compact( 'plugin', 'file' ), admin_url( 'plugin-editor.php' ) );
 564          } elseif ( $stylesheet ) {
 565              $url = add_query_arg(
 566                  array(
 567                      'theme' => $stylesheet,
 568                      'file'  => $file,
 569                  ),
 570                  admin_url( 'theme-editor.php' )
 571              );
 572          } else {
 573              $url = admin_url();
 574          }
 575  
 576          if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
 577              /*
 578               * Close any active session to prevent HTTP requests from timing out
 579               * when attempting to connect back to the site.
 580               */
 581              session_write_close();
 582          }
 583  
 584          $url = add_query_arg( $scrape_params, $url );
 585  
 586          /** This filter is documented in wp-includes/class-wp-http-streams.php */
 587          $sslverify = apply_filters( 'https_local_ssl_verify', false, $url );
 588  
 589          $r                      = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
 590          $body                   = wp_remote_retrieve_body( $r );
 591          $scrape_result_position = strpos( $body, $needle_start );
 592  
 593          $loopback_request_failure = array(
 594              'code'    => 'loopback_request_failed',
 595              'message' => __( 'Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.' ),
 596          );
 597          $json_parse_failure       = array(
 598              'code' => 'json_parse_error',
 599          );
 600  
 601          $result = null;
 602  
 603          if ( false === $scrape_result_position ) {
 604              $result = $loopback_request_failure;
 605          } else {
 606              $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
 607              $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
 608              $result       = json_decode( trim( $error_output ), true );
 609              if ( empty( $result ) ) {
 610                  $result = $json_parse_failure;
 611              }
 612          }
 613  
 614          // Try making request to homepage as well to see if visitors have been whitescreened.
 615          if ( true === $result ) {
 616              $url                    = home_url( '/' );
 617              $url                    = add_query_arg( $scrape_params, $url );
 618              $r                      = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
 619              $body                   = wp_remote_retrieve_body( $r );
 620              $scrape_result_position = strpos( $body, $needle_start );
 621  
 622              if ( false === $scrape_result_position ) {
 623                  $result = $loopback_request_failure;
 624              } else {
 625                  $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
 626                  $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
 627                  $result       = json_decode( trim( $error_output ), true );
 628                  if ( empty( $result ) ) {
 629                      $result = $json_parse_failure;
 630                  }
 631              }
 632          }
 633  
 634          delete_transient( $transient );
 635  
 636          if ( true !== $result ) {
 637              // Roll-back file change.
 638              file_put_contents( $real_file, $previous_content );
 639              wp_opcache_invalidate( $real_file, true );
 640  
 641              if ( ! isset( $result['message'] ) ) {
 642                  $message = __( 'An error occurred. Please try again later.' );
 643              } else {
 644                  $message = $result['message'];
 645                  unset( $result['message'] );
 646              }
 647  
 648              return new WP_Error( 'php_error', $message, $result );
 649          }
 650      }
 651  
 652      if ( $theme instanceof WP_Theme ) {
 653          $theme->cache_delete();
 654      }
 655  
 656      return true;
 657  }
 658  
 659  
 660  /**
 661   * Returns a filename of a temporary unique file.
 662   *
 663   * Please note that the calling function must delete or move the file.
 664   *
 665   * The filename is based off the passed parameter or defaults to the current unix timestamp,
 666   * while the directory can either be passed as well, or by leaving it blank, default to a writable
 667   * temporary directory.
 668   *
 669   * @since 2.6.0
 670   *
 671   * @param string $filename Optional. Filename to base the Unique file off. Default empty.
 672   * @param string $dir      Optional. Directory to store the file in. Default empty.
 673   * @return string A writable filename.
 674   */
 675  function wp_tempnam( $filename = '', $dir = '' ) {
 676      if ( empty( $dir ) ) {
 677          $dir = get_temp_dir();
 678      }
 679  
 680      if ( empty( $filename ) || in_array( $filename, array( '.', '/', '\\' ), true ) ) {
 681          $filename = uniqid();
 682      }
 683  
 684      // Use the basename of the given file without the extension as the name for the temporary directory.
 685      $temp_filename = basename( $filename );
 686      $temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename );
 687  
 688      // If the folder is falsey, use its parent directory name instead.
 689      if ( ! $temp_filename ) {
 690          return wp_tempnam( dirname( $filename ), $dir );
 691      }
 692  
 693      // Suffix some random data to avoid filename conflicts.
 694      $temp_filename .= '-' . wp_generate_password( 6, false );
 695      $temp_filename .= '.tmp';
 696      $temp_filename  = wp_unique_filename( $dir, $temp_filename );
 697  
 698      /*
 699       * Filesystems typically have a limit of 255 characters for a filename.
 700       *
 701       * If the generated unique filename exceeds this, truncate the initial
 702       * filename and try again.
 703       *
 704       * As it's possible that the truncated filename may exist, producing a
 705       * suffix of "-1" or "-10" which could exceed the limit again, truncate
 706       * it to 252 instead.
 707       */
 708      $characters_over_limit = strlen( $temp_filename ) - 252;
 709      if ( $characters_over_limit > 0 ) {
 710          $filename = substr( $filename, 0, -$characters_over_limit );
 711          return wp_tempnam( $filename, $dir );
 712      }
 713  
 714      $temp_filename = $dir . $temp_filename;
 715  
 716      $fp = @fopen( $temp_filename, 'x' );
 717  
 718      if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) {
 719          return wp_tempnam( $filename, $dir );
 720      }
 721  
 722      if ( $fp ) {
 723          fclose( $fp );
 724      }
 725  
 726      return $temp_filename;
 727  }
 728  
 729  /**
 730   * Makes sure that the file that was requested to be edited is allowed to be edited.
 731   *
 732   * Function will die if you are not allowed to edit the file.
 733   *
 734   * @since 1.5.0
 735   *
 736   * @param string   $file          File the user is attempting to edit.
 737   * @param string[] $allowed_files Optional. Array of allowed files to edit.
 738   *                                `$file` must match an entry exactly.
 739   * @return string|null Returns the file name on success, null in case of absolute Windows drive paths, and dies on failure.
 740   */
 741  function validate_file_to_edit( $file, $allowed_files = array() ) {
 742      $code = validate_file( $file, $allowed_files );
 743  
 744      if ( ! $code ) {
 745          return $file;
 746      }
 747  
 748      switch ( $code ) {
 749          case 1:
 750              wp_die( __( 'Sorry, that file cannot be edited.' ) );
 751  
 752              // case 2 :
 753              // wp_die( __('Sorry, cannot call files with their real path.' ));
 754  
 755          case 3:
 756              wp_die( __( 'Sorry, that file cannot be edited.' ) );
 757      }
 758      return null;
 759  }
 760  
 761  /**
 762   * Handles PHP uploads in WordPress.
 763   *
 764   * Sanitizes file names, checks extensions for mime type, and moves the file
 765   * to the appropriate directory within the uploads directory.
 766   *
 767   * @access private
 768   * @since 4.0.0
 769   *
 770   * @see wp_handle_upload_error
 771   *
 772   * @param array       $file      {
 773   *     Reference to a single element from `$_FILES`. Call the function once for each uploaded file.
 774   *
 775   *     @type string $name     The original name of the file on the client machine.
 776   *     @type string $type     The mime type of the file, if the browser provided this information.
 777   *     @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
 778   *     @type int    $size     The size, in bytes, of the uploaded file.
 779   *     @type int    $error    The error code associated with this file upload.
 780   * }
 781   * @param array|false $overrides {
 782   *     An array of override parameters for this file, or boolean false if none are provided.
 783   *
 784   *     @type callable $upload_error_handler     Function to call when there is an error during the upload process.
 785   *                                              See {@see wp_handle_upload_error()}.
 786   *     @type callable $unique_filename_callback Function to call when determining a unique file name for the file.
 787   *                                              See {@see wp_unique_filename()}.
 788   *     @type string[] $upload_error_strings     The strings that describe the error indicated in
 789   *                                              `$_FILES[{form field}]['error']`.
 790   *     @type bool     $test_form                Whether to test that the `$_POST['action']` parameter is as expected.
 791   *     @type bool     $test_size                Whether to test that the file size is greater than zero bytes.
 792   *     @type bool     $test_type                Whether to test that the mime type of the file is as expected.
 793   *     @type string[] $mimes                    Array of allowed mime types keyed by their file extension regex.
 794   * }
 795   * @param string      $time      Time formatted in 'yyyy/mm'.
 796   * @param string      $action    Expected value for `$_POST['action']`.
 797   * @return array {
 798   *     On success, returns an associative array of file attributes.
 799   *     On failure, returns `$overrides['upload_error_handler']( &$file, $message )`
 800   *     or `array( 'error' => $message )`.
 801   *
 802   *     @type string $file Filename of the newly-uploaded file.
 803   *     @type string $url  URL of the newly-uploaded file.
 804   *     @type string $type Mime type of the newly-uploaded file.
 805   * }
 806   *
 807   * @phpstan-return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string }
 808   *                |array{ error: non-empty-string }
 809   */
 810  function _wp_handle_upload( &$file, $overrides, $time, $action ) {
 811      // The default error handler.
 812      if ( ! function_exists( 'wp_handle_upload_error' ) ) {
 813  		function wp_handle_upload_error( &$file, $message ) {
 814              return array( 'error' => $message );
 815          }
 816      }
 817  
 818      /**
 819       * Filters the data for a file before it is uploaded to WordPress.
 820       *
 821       * The dynamic portion of the hook name, `$action`, refers to the post action.
 822       *
 823       * Possible hook names include:
 824       *
 825       *  - `wp_handle_sideload_prefilter`
 826       *  - `wp_handle_upload_prefilter`
 827       *
 828       * @since 2.9.0 as 'wp_handle_upload_prefilter'.
 829       * @since 4.0.0 Converted to a dynamic hook with `$action`.
 830       *
 831       * @param array $file {
 832       *     Reference to a single element from `$_FILES`.
 833       *
 834       *     @type string $name     The original name of the file on the client machine.
 835       *     @type string $type     The mime type of the file, if the browser provided this information.
 836       *     @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
 837       *     @type int    $size     The size, in bytes, of the uploaded file.
 838       *     @type int    $error    The error code associated with this file upload.
 839       * }
 840       */
 841      $file = apply_filters( "{$action}_prefilter", $file );
 842  
 843      /**
 844       * Filters the override parameters for a file before it is uploaded to WordPress.
 845       *
 846       * The dynamic portion of the hook name, `$action`, refers to the post action.
 847       *
 848       * Possible hook names include:
 849       *
 850       *  - `wp_handle_sideload_overrides`
 851       *  - `wp_handle_upload_overrides`
 852       *
 853       * @since 5.7.0
 854       *
 855       * @param array|false $overrides An array of override parameters for this file. Boolean false if none are
 856       *                               provided. See {@see _wp_handle_upload()}.
 857       * @param array       $file      {
 858       *     Reference to a single element from `$_FILES`.
 859       *
 860       *     @type string $name     The original name of the file on the client machine.
 861       *     @type string $type     The mime type of the file, if the browser provided this information.
 862       *     @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
 863       *     @type int    $size     The size, in bytes, of the uploaded file.
 864       *     @type int    $error    The error code associated with this file upload.
 865       * }
 866       */
 867      $overrides = apply_filters( "{$action}_overrides", $overrides, $file );
 868  
 869      // You may define your own function and pass the name in $overrides['upload_error_handler'].
 870      $upload_error_handler = 'wp_handle_upload_error';
 871      if ( isset( $overrides['upload_error_handler'] ) ) {
 872          $upload_error_handler = $overrides['upload_error_handler'];
 873      }
 874  
 875      // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
 876      if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) {
 877          return call_user_func_array( $upload_error_handler, array( &$file, $file['error'] ) );
 878      }
 879  
 880      // Install user overrides. Did we mention that this voids your warranty?
 881  
 882      // You may define your own function and pass the name in $overrides['unique_filename_callback'].
 883      $unique_filename_callback = null;
 884      if ( isset( $overrides['unique_filename_callback'] ) ) {
 885          $unique_filename_callback = $overrides['unique_filename_callback'];
 886      }
 887  
 888      /*
 889       * This may not have originally been intended to be overridable,
 890       * but historically has been.
 891       */
 892      if ( isset( $overrides['upload_error_strings'] ) ) {
 893          $upload_error_strings = $overrides['upload_error_strings'];
 894      } else {
 895          // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
 896          $upload_error_strings = array(
 897              false,
 898              sprintf(
 899                  /* translators: 1: upload_max_filesize, 2: php.ini */
 900                  __( 'The uploaded file exceeds the %1$s directive in %2$s.' ),
 901                  'upload_max_filesize',
 902                  'php.ini'
 903              ),
 904              sprintf(
 905                  /* translators: %s: MAX_FILE_SIZE */
 906                  __( 'The uploaded file exceeds the %s directive that was specified in the HTML form.' ),
 907                  'MAX_FILE_SIZE'
 908              ),
 909              __( 'The uploaded file was only partially uploaded.' ),
 910              __( 'No file was uploaded.' ),
 911              '',
 912              __( 'Missing a temporary folder.' ),
 913              __( 'Failed to write file to disk.' ),
 914              __( 'File upload stopped by extension.' ),
 915          );
 916      }
 917  
 918      // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
 919      $test_form = $overrides['test_form'] ?? true;
 920      $test_size = $overrides['test_size'] ?? true;
 921  
 922      // If you override this, you must provide $ext and $type!!
 923      $test_type = $overrides['test_type'] ?? true;
 924      $mimes     = $overrides['mimes'] ?? null;
 925  
 926      // A correct form post will pass this test.
 927      if ( $test_form && ( ! isset( $_POST['action'] ) || $_POST['action'] !== $action ) ) {
 928          return call_user_func_array( $upload_error_handler, array( &$file, __( 'Invalid form submission.' ) ) );
 929      }
 930  
 931      // A successful upload will pass this test. It makes no sense to override this one.
 932      if ( isset( $file['error'] ) && $file['error'] > 0 ) {
 933          return call_user_func_array( $upload_error_handler, array( &$file, $upload_error_strings[ $file['error'] ] ) );
 934      }
 935  
 936      // A properly uploaded file will pass this test. There should be no reason to override this one.
 937      $test_uploaded_file = 'wp_handle_upload' === $action ? is_uploaded_file( $file['tmp_name'] ) : @is_readable( $file['tmp_name'] );
 938      if ( ! $test_uploaded_file ) {
 939          return call_user_func_array( $upload_error_handler, array( &$file, __( 'Specified file failed upload test.' ) ) );
 940      }
 941  
 942      $test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] );
 943      // A non-empty file will pass this test.
 944      if ( $test_size && ! ( $test_file_size > 0 ) ) {
 945          if ( is_multisite() ) {
 946              $error_msg = __( 'File is empty. Please upload something more substantial.' );
 947          } else {
 948              $error_msg = sprintf(
 949                  /* translators: 1: php.ini, 2: post_max_size, 3: upload_max_filesize */
 950                  __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your %1$s file or by %2$s being defined as smaller than %3$s in %1$s.' ),
 951                  'php.ini',
 952                  'post_max_size',
 953                  'upload_max_filesize'
 954              );
 955          }
 956  
 957          return call_user_func_array( $upload_error_handler, array( &$file, $error_msg ) );
 958      }
 959  
 960      // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
 961      if ( $test_type ) {
 962          $wp_filetype     = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
 963          $ext             = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
 964          $type            = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
 965          $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
 966  
 967          // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect.
 968          if ( $proper_filename ) {
 969              $file['name'] = $proper_filename;
 970          }
 971  
 972          if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
 973              return call_user_func_array( $upload_error_handler, array( &$file, __( 'Sorry, you are not allowed to upload this file type.' ) ) );
 974          }
 975  
 976          if ( ! $type ) {
 977              $type = $file['type'];
 978          }
 979      } else {
 980          $type = '';
 981      }
 982  
 983      /*
 984       * A writable uploads dir will pass this test. Again, there's no point
 985       * overriding this one.
 986       */
 987      $uploads = wp_upload_dir( $time );
 988      if ( ! ( $uploads && false === $uploads['error'] ) ) {
 989          return call_user_func_array( $upload_error_handler, array( &$file, $uploads['error'] ) );
 990      }
 991  
 992      $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
 993  
 994      // Move the file to the uploads dir.
 995      $new_file = $uploads['path'] . "/$filename";
 996  
 997      /**
 998       * Filters whether to short-circuit moving the uploaded file after passing all checks.
 999       *
1000       * If a non-null value is returned from the filter, moving the file and any related
1001       * error reporting will be completely skipped.
1002       *
1003       * @since 4.9.0
1004       *
1005       * @param mixed    $move_new_file If null (default) move the file after the upload.
1006       * @param array    $file          {
1007       *     Reference to a single element from `$_FILES`.
1008       *
1009       *     @type string $name     The original name of the file on the client machine.
1010       *     @type string $type     The mime type of the file, if the browser provided this information.
1011       *     @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
1012       *     @type int    $size     The size, in bytes, of the uploaded file.
1013       *     @type int    $error    The error code associated with this file upload.
1014       * }
1015       * @param string   $new_file      Filename of the newly-uploaded file.
1016       * @param string   $type          Mime type of the newly-uploaded file.
1017       */
1018      $move_new_file = apply_filters( 'pre_move_uploaded_file', null, $file, $new_file, $type );
1019  
1020      if ( null === $move_new_file ) {
1021          if ( 'wp_handle_upload' === $action ) {
1022              $move_new_file = @move_uploaded_file( $file['tmp_name'], $new_file );
1023          } else {
1024              // Use copy and unlink because rename breaks streams.
1025              // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
1026              $move_new_file = @copy( $file['tmp_name'], $new_file );
1027              unlink( $file['tmp_name'] );
1028          }
1029  
1030          if ( false === $move_new_file ) {
1031              if ( str_starts_with( $uploads['basedir'], ABSPATH ) ) {
1032                  $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
1033              } else {
1034                  $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
1035              }
1036  
1037              return $upload_error_handler(
1038                  $file,
1039                  sprintf(
1040                      /* translators: %s: Destination file path. */
1041                      __( 'The uploaded file could not be moved to %s.' ),
1042                      $error_path
1043                  )
1044              );
1045          }
1046      }
1047  
1048      // Set correct file permissions.
1049      $stat  = stat( dirname( $new_file ) );
1050      $perms = $stat['mode'] & 0000666;
1051      chmod( $new_file, $perms );
1052  
1053      // Compute the URL.
1054      $url = $uploads['url'] . "/$filename";
1055  
1056      if ( is_multisite() ) {
1057          clean_dirsize_cache( $new_file );
1058      }
1059  
1060      /**
1061       * Filters the data array for the uploaded file.
1062       *
1063       * @since 2.1.0
1064       *
1065       * @param array  $upload {
1066       *     Array of upload data.
1067       *
1068       *     @type string $file Filename of the newly-uploaded file.
1069       *     @type string $url  URL of the newly-uploaded file.
1070       *     @type string $type Mime type of the newly-uploaded file.
1071       * }
1072       * @param string $context The type of upload action. Values include 'upload' or 'sideload'.
1073       */
1074      return apply_filters(
1075          'wp_handle_upload',
1076          array(
1077              'file' => $new_file,
1078              'url'  => $url,
1079              'type' => $type,
1080          ),
1081          'wp_handle_sideload' === $action ? 'sideload' : 'upload'
1082      );
1083  }
1084  
1085  /**
1086   * Wrapper for _wp_handle_upload().
1087   *
1088   * Passes the {@see 'wp_handle_upload'} action.
1089   *
1090   * @since 2.0.0
1091   *
1092   * @see _wp_handle_upload()
1093   *
1094   * @param array       $file      Reference to a single element of `$_FILES`.
1095   *                               Call the function once for each uploaded file.
1096   *                               See _wp_handle_upload() for accepted values.
1097   * @param array|false $overrides Optional. An associative array of names => values
1098   *                               to override default variables. Default false.
1099   *                               See _wp_handle_upload() for accepted values.
1100   * @param string|null $time      Optional. Time formatted in 'yyyy/mm'. Default null.
1101   * @return array See _wp_handle_upload() for return value.
1102   *
1103   * @phpstan-return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string }
1104   *                |array{ error: non-empty-string }
1105   */
1106  function wp_handle_upload( &$file, $overrides = false, $time = null ) {
1107      /*
1108       *  $_POST['action'] must be set and its value must equal $overrides['action']
1109       *  or this:
1110       */
1111      $action = $overrides['action'] ?? 'wp_handle_upload';
1112      return _wp_handle_upload( $file, $overrides, $time, $action );
1113  }
1114  
1115  /**
1116   * Wrapper for _wp_handle_upload().
1117   *
1118   * Passes the {@see 'wp_handle_sideload'} action.
1119   *
1120   * @since 2.6.0
1121   *
1122   * @see _wp_handle_upload()
1123   *
1124   * @param array       $file      Reference to a single element of `$_FILES`.
1125   *                               Call the function once for each uploaded file.
1126   *                               See _wp_handle_upload() for accepted values.
1127   * @param array|false $overrides Optional. An associative array of names => values
1128   *                               to override default variables. Default false.
1129   *                               See _wp_handle_upload() for accepted values.
1130   * @param string|null $time      Optional. Time formatted in 'yyyy/mm'. Default null.
1131   * @return array See _wp_handle_upload() for return value.
1132   *
1133   * @phpstan-return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string }
1134   *                |array{ error: non-empty-string }
1135   */
1136  function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
1137      /*
1138       *  $_POST['action'] must be set and its value must equal $overrides['action']
1139       *  or this:
1140       */
1141      $action = $overrides['action'] ?? 'wp_handle_sideload';
1142      return _wp_handle_upload( $file, $overrides, $time, $action );
1143  }
1144  
1145  /**
1146   * Downloads a URL to a local temporary file using the WordPress HTTP API.
1147   *
1148   * Please note that the calling function must delete or move the file.
1149   *
1150   * @since 2.5.0
1151   * @since 5.2.0 Signature Verification with SoftFail was added.
1152   * @since 5.9.0 Support for Content-Disposition filename was added.
1153   *
1154   * @param string $url                    The URL of the file to download.
1155   * @param int    $timeout                The timeout for the request to download the file.
1156   *                                       Default 300 seconds.
1157   * @param bool   $signature_verification Whether to perform Signature Verification.
1158   *                                       Default false.
1159   * @return string|WP_Error Filename on success, WP_Error on failure.
1160   */
1161  function download_url( $url, $timeout = 300, $signature_verification = false ) {
1162      // WARNING: The file is not automatically deleted, the script must delete or move the file.
1163      if ( ! $url ) {
1164          return new WP_Error( 'http_no_url', __( 'No URL Provided.' ) );
1165      }
1166  
1167      $url_path     = parse_url( $url, PHP_URL_PATH );
1168      $url_filename = '';
1169      if ( is_string( $url_path ) && '' !== $url_path ) {
1170          $url_filename = basename( $url_path );
1171      }
1172  
1173      $tmpfname = wp_tempnam( $url_filename );
1174      if ( ! $tmpfname ) {
1175          return new WP_Error( 'http_no_file', __( 'Could not create temporary file.' ) );
1176      }
1177  
1178      $response = wp_safe_remote_get(
1179          $url,
1180          array(
1181              'timeout'  => $timeout,
1182              'stream'   => true,
1183              'filename' => $tmpfname,
1184          )
1185      );
1186  
1187      if ( is_wp_error( $response ) ) {
1188          unlink( $tmpfname );
1189          return $response;
1190      }
1191  
1192      $response_code = wp_remote_retrieve_response_code( $response );
1193  
1194      if ( 200 !== $response_code ) {
1195          $data = array(
1196              'code' => $response_code,
1197          );
1198  
1199          // Retrieve a sample of the response body for debugging purposes.
1200          $tmpf = fopen( $tmpfname, 'rb' );
1201  
1202          if ( $tmpf ) {
1203              /**
1204               * Filters the maximum error response body size in `download_url()`.
1205               *
1206               * @since 5.1.0
1207               *
1208               * @see download_url()
1209               *
1210               * @param int $size The maximum error response body size. Default 1 KB.
1211               */
1212              $response_size = apply_filters( 'download_url_error_max_body_size', KB_IN_BYTES );
1213  
1214              $data['body'] = fread( $tmpf, $response_size );
1215              fclose( $tmpf );
1216          }
1217  
1218          unlink( $tmpfname );
1219  
1220          return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ), $data );
1221      }
1222  
1223      $content_disposition = wp_remote_retrieve_header( $response, 'Content-Disposition' );
1224  
1225      if ( $content_disposition ) {
1226          $content_disposition = strtolower( $content_disposition );
1227  
1228          if ( str_starts_with( $content_disposition, 'attachment; filename=' ) ) {
1229              $tmpfname_disposition = sanitize_file_name( substr( $content_disposition, 21 ) );
1230          } else {
1231              $tmpfname_disposition = '';
1232          }
1233  
1234          // Potential file name must be valid string.
1235          if ( $tmpfname_disposition && is_string( $tmpfname_disposition )
1236              && ( 0 === validate_file( $tmpfname_disposition ) )
1237          ) {
1238              $tmpfname_disposition = dirname( $tmpfname ) . '/' . $tmpfname_disposition;
1239  
1240              if ( rename( $tmpfname, $tmpfname_disposition ) ) {
1241                  $tmpfname = $tmpfname_disposition;
1242              }
1243  
1244              if ( ( $tmpfname !== $tmpfname_disposition ) && file_exists( $tmpfname_disposition ) ) {
1245                  unlink( $tmpfname_disposition );
1246              }
1247          }
1248      }
1249  
1250      $mime_type = wp_remote_retrieve_header( $response, 'content-type' );
1251      if ( $mime_type && 'tmp' === pathinfo( $tmpfname, PATHINFO_EXTENSION ) ) {
1252          $valid_mime_types = array_flip( get_allowed_mime_types() );
1253          if ( ! empty( $valid_mime_types[ $mime_type ] ) ) {
1254              $extensions     = explode( '|', $valid_mime_types[ $mime_type ] );
1255              $new_image_name = substr( $tmpfname, 0, -4 ) . ".{$extensions[0]}";
1256              if ( 0 === validate_file( $new_image_name ) ) {
1257                  if ( rename( $tmpfname, $new_image_name ) ) {
1258                      $tmpfname = $new_image_name;
1259                  }
1260  
1261                  if ( ( $tmpfname !== $new_image_name ) && file_exists( $new_image_name ) ) {
1262                      unlink( $new_image_name );
1263                  }
1264              }
1265          }
1266      }
1267  
1268      $content_md5 = wp_remote_retrieve_header( $response, 'Content-MD5' );
1269  
1270      if ( $content_md5 ) {
1271          $md5_check = verify_file_md5( $tmpfname, $content_md5 );
1272  
1273          if ( is_wp_error( $md5_check ) ) {
1274              unlink( $tmpfname );
1275              return $md5_check;
1276          }
1277      }
1278  
1279      // If the caller expects signature verification to occur, check to see if this URL supports it.
1280      if ( $signature_verification ) {
1281          /**
1282           * Filters the list of hosts which should have Signature Verification attempted on.
1283           *
1284           * @since 5.2.0
1285           *
1286           * @param string[] $hostnames List of hostnames.
1287           */
1288          $signed_hostnames = apply_filters( 'wp_signature_hosts', array( 'wordpress.org', 'downloads.wordpress.org', 's.w.org' ) );
1289  
1290          $signature_verification = in_array( parse_url( $url, PHP_URL_HOST ), $signed_hostnames, true );
1291      }
1292  
1293      // Perform signature validation if supported.
1294      if ( $signature_verification ) {
1295          $signature = wp_remote_retrieve_header( $response, 'X-Content-Signature' );
1296  
1297          if ( ! $signature ) {
1298              /*
1299               * Retrieve signatures from a file if the header wasn't included.
1300               * WordPress.org stores signatures at $package_url.sig.
1301               */
1302  
1303              $signature_url = false;
1304  
1305              if ( is_string( $url_path ) && ( str_ends_with( $url_path, '.zip' ) || str_ends_with( $url_path, '.tar.gz' ) ) ) {
1306                  $signature_url = str_replace( $url_path, $url_path . '.sig', $url );
1307              }
1308  
1309              /**
1310               * Filters the URL where the signature for a file is located.
1311               *
1312               * @since 5.2.0
1313               *
1314               * @param false|string $signature_url The URL where signatures can be found for a file, or false if none are known.
1315               * @param string       $url           The URL being verified.
1316               */
1317              $signature_url = apply_filters( 'wp_signature_url', $signature_url, $url );
1318  
1319              if ( $signature_url ) {
1320                  $signature_request = wp_safe_remote_get(
1321                      $signature_url,
1322                      array(
1323                          'limit_response_size' => 10 * KB_IN_BYTES, // 10KB should be large enough for quite a few signatures.
1324                      )
1325                  );
1326  
1327                  if ( ! is_wp_error( $signature_request ) && 200 === wp_remote_retrieve_response_code( $signature_request ) ) {
1328                      $signature = explode( "\n", wp_remote_retrieve_body( $signature_request ) );
1329                  }
1330              }
1331          }
1332  
1333          // Perform the checks.
1334          $signature_verification = verify_file_signature( $tmpfname, $signature, $url_filename );
1335      }
1336  
1337      if ( is_wp_error( $signature_verification ) ) {
1338          if (
1339              /**
1340               * Filters whether Signature Verification failures should be allowed to soft fail.
1341               *
1342               * WARNING: This may be removed from a future release.
1343               *
1344               * @since 5.2.0
1345               *
1346               * @param bool   $signature_softfail If a softfail is allowed.
1347               * @param string $url                The url being accessed.
1348               */
1349              apply_filters( 'wp_signature_softfail', true, $url )
1350          ) {
1351              $signature_verification->add_data( $tmpfname, 'softfail-filename' );
1352          } else {
1353              // Hard-fail.
1354              unlink( $tmpfname );
1355          }
1356  
1357          return $signature_verification;
1358      }
1359  
1360      return $tmpfname;
1361  }
1362  
1363  /**
1364   * Calculates and compares the MD5 of a file to its expected value.
1365   *
1366   * @since 3.7.0
1367   *
1368   * @param string $filename     The filename to check the MD5 of.
1369   * @param string $expected_md5 The expected MD5 of the file, either a base64-encoded raw md5,
1370   *                             or a hex-encoded md5.
1371   * @return bool|WP_Error True on success, false when the MD5 format is unknown/unexpected,
1372   *                       WP_Error on failure.
1373   */
1374  function verify_file_md5( $filename, $expected_md5 ) {
1375      if ( 32 === strlen( $expected_md5 ) ) {
1376          $expected_raw_md5 = pack( 'H*', $expected_md5 );
1377      } elseif ( 24 === strlen( $expected_md5 ) ) {
1378          $expected_raw_md5 = base64_decode( $expected_md5 );
1379      } else {
1380          return false; // Unknown format.
1381      }
1382  
1383      $file_md5 = md5_file( $filename, true );
1384  
1385      if ( $file_md5 === $expected_raw_md5 ) {
1386          return true;
1387      }
1388  
1389      return new WP_Error(
1390          'md5_mismatch',
1391          sprintf(
1392              /* translators: 1: File checksum, 2: Expected checksum value. */
1393              __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ),
1394              bin2hex( $file_md5 ),
1395              bin2hex( $expected_raw_md5 )
1396          )
1397      );
1398  }
1399  
1400  /**
1401   * Verifies the contents of a file against its ED25519 signature.
1402   *
1403   * @since 5.2.0
1404   *
1405   * @param string       $filename            The file to validate.
1406   * @param string|array $signatures          A Signature provided for the file.
1407   * @param string|false $filename_for_errors Optional. A friendly filename for errors.
1408   * @return bool|WP_Error True on success, false if verification not attempted,
1409   *                       or WP_Error describing an error condition.
1410   */
1411  function verify_file_signature( $filename, $signatures, $filename_for_errors = false ) {
1412      if ( ! $filename_for_errors ) {
1413          $filename_for_errors = wp_basename( $filename );
1414      }
1415  
1416      // Check we can process signatures.
1417      if ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) || ! in_array( 'sha384', array_map( 'strtolower', hash_algos() ), true ) ) {
1418          return new WP_Error(
1419              'signature_verification_unsupported',
1420              sprintf(
1421                  /* translators: %s: The filename of the package. */
1422                  __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
1423                  '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1424              ),
1425              ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) ? 'sodium_crypto_sign_verify_detached' : 'sha384' )
1426          );
1427      }
1428  
1429      // Verify runtime speed of Sodium_Compat is acceptable.
1430      if ( ! extension_loaded( 'sodium' ) && ! ParagonIE_Sodium_Compat::polyfill_is_fast() ) {
1431          $sodium_compat_is_fast = false;
1432  
1433          // Allow for an old version of Sodium_Compat being loaded before the bundled WordPress one.
1434          if ( method_exists( 'ParagonIE_Sodium_Compat', 'runtime_speed_test' ) ) {
1435              /*
1436               * Run `ParagonIE_Sodium_Compat::runtime_speed_test()` in optimized integer mode,
1437               * as that's what WordPress utilizes during signing verifications.
1438               */
1439              // phpcs:disable WordPress.NamingConventions.ValidVariableName
1440              $old_fastMult                      = ParagonIE_Sodium_Compat::$fastMult;
1441              ParagonIE_Sodium_Compat::$fastMult = true;
1442              $sodium_compat_is_fast             = ParagonIE_Sodium_Compat::runtime_speed_test( 100, 10 );
1443              ParagonIE_Sodium_Compat::$fastMult = $old_fastMult;
1444              // phpcs:enable
1445          }
1446  
1447          /*
1448           * This cannot be performed in a reasonable amount of time.
1449           * https://github.com/paragonie/sodium_compat#help-sodium_compat-is-slow-how-can-i-make-it-fast
1450           */
1451          if ( ! $sodium_compat_is_fast ) {
1452              return new WP_Error(
1453                  'signature_verification_unsupported',
1454                  sprintf(
1455                      /* translators: %s: The filename of the package. */
1456                      __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
1457                      '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1458                  ),
1459                  array(
1460                      'php'                => PHP_VERSION,
1461                      'sodium'             => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
1462                      'polyfill_is_fast'   => false,
1463                      'max_execution_time' => ini_get( 'max_execution_time' ),
1464                  )
1465              );
1466          }
1467      }
1468  
1469      if ( ! $signatures ) {
1470          return new WP_Error(
1471              'signature_verification_no_signature',
1472              sprintf(
1473                  /* translators: %s: The filename of the package. */
1474                  __( 'The authenticity of %s could not be verified as no signature was found.' ),
1475                  '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1476              ),
1477              array(
1478                  'filename' => $filename_for_errors,
1479              )
1480          );
1481      }
1482  
1483      $trusted_keys = wp_trusted_keys();
1484      $file_hash    = hash_file( 'sha384', $filename, true );
1485  
1486      mbstring_binary_safe_encoding();
1487  
1488      $skipped_key       = 0;
1489      $skipped_signature = 0;
1490  
1491      foreach ( (array) $signatures as $signature ) {
1492          $signature_raw = base64_decode( $signature );
1493  
1494          // Ensure only valid-length signatures are considered.
1495          if ( SODIUM_CRYPTO_SIGN_BYTES !== strlen( $signature_raw ) ) {
1496              ++$skipped_signature;
1497              continue;
1498          }
1499  
1500          foreach ( (array) $trusted_keys as $key ) {
1501              $key_raw = base64_decode( $key );
1502  
1503              // Only pass valid public keys through.
1504              if ( SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES !== strlen( $key_raw ) ) {
1505                  ++$skipped_key;
1506                  continue;
1507              }
1508  
1509              if ( sodium_crypto_sign_verify_detached( $signature_raw, $file_hash, $key_raw ) ) {
1510                  reset_mbstring_encoding();
1511                  return true;
1512              }
1513          }
1514      }
1515  
1516      reset_mbstring_encoding();
1517  
1518      return new WP_Error(
1519          'signature_verification_failed',
1520          sprintf(
1521              /* translators: %s: The filename of the package. */
1522              __( 'The authenticity of %s could not be verified.' ),
1523              '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1524          ),
1525          // Error data helpful for debugging:
1526          array(
1527              'filename'    => $filename_for_errors,
1528              'keys'        => $trusted_keys,
1529              'signatures'  => $signatures,
1530              'hash'        => bin2hex( $file_hash ),
1531              'skipped_key' => $skipped_key,
1532              'skipped_sig' => $skipped_signature,
1533              'php'         => PHP_VERSION,
1534              'sodium'      => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
1535          )
1536      );
1537  }
1538  
1539  /**
1540   * Retrieves the list of signing keys trusted by WordPress.
1541   *
1542   * @since 5.2.0
1543   *
1544   * @return string[] Array of base64-encoded signing keys.
1545   */
1546  function wp_trusted_keys() {
1547      $trusted_keys = array();
1548  
1549      if ( time() < 1617235200 ) {
1550          // WordPress.org Key #1 - This key is only valid before April 1st, 2021.
1551          $trusted_keys[] = 'fRPyrxb/MvVLbdsYi+OOEv4xc+Eqpsj+kkAS6gNOkI0=';
1552      }
1553  
1554      // TODO: Add key #2 with longer expiration.
1555  
1556      /**
1557       * Filters the valid signing keys used to verify the contents of files.
1558       *
1559       * @since 5.2.0
1560       *
1561       * @param string[] $trusted_keys The trusted keys that may sign packages.
1562       */
1563      return apply_filters( 'wp_trusted_keys', $trusted_keys );
1564  }
1565  
1566  /**
1567   * Determines whether the given file is a valid ZIP file.
1568   *
1569   * This function does not test to ensure that a file exists. Non-existent files
1570   * are not valid ZIPs, so those will also return false.
1571   *
1572   * @since 6.4.4
1573   *
1574   * @param string $file Full path to the ZIP file.
1575   * @return bool Whether the file is a valid ZIP file.
1576   */
1577  function wp_zip_file_is_valid( $file ) {
1578      /** This filter is documented in wp-admin/includes/file.php */
1579      if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
1580          $archive          = new ZipArchive();
1581          $archive_is_valid = $archive->open( $file, ZipArchive::CHECKCONS );
1582          if ( true === $archive_is_valid ) {
1583              $archive->close();
1584              return true;
1585          }
1586      }
1587  
1588      // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
1589      require_once  ABSPATH . 'wp-admin/includes/class-pclzip.php';
1590  
1591      $archive          = new PclZip( $file );
1592      $archive_is_valid = is_array( $archive->properties() );
1593  
1594      return $archive_is_valid;
1595  }
1596  
1597  /**
1598   * Unzips a specified ZIP file to a location on the filesystem via the WordPress
1599   * Filesystem Abstraction.
1600   *
1601   * Assumes that WP_Filesystem() has already been called and set up. Does not extract
1602   * a root-level __MACOSX directory, if present.
1603   *
1604   * Attempts to increase the PHP memory limit to 256M before uncompressing. However,
1605   * the most memory required shouldn't be much larger than the archive itself.
1606   *
1607   * @since 2.5.0
1608   *
1609   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1610   *
1611   * @param string $file Full path and filename of ZIP archive.
1612   * @param string $to   Full path on the filesystem to extract archive to.
1613   * @return true|WP_Error True on success, WP_Error on failure.
1614   */
1615  function unzip_file( $file, $to ) {
1616      global $wp_filesystem;
1617  
1618      if ( ! $wp_filesystem || ! is_object( $wp_filesystem ) ) {
1619          return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
1620      }
1621  
1622      // Unzip can use a lot of memory, but not this much hopefully.
1623      wp_raise_memory_limit( 'admin' );
1624  
1625      $needed_dirs = array();
1626      $to          = trailingslashit( $to );
1627  
1628      // Determine any parent directories needed (of the upgrade directory).
1629      if ( ! $wp_filesystem->is_dir( $to ) ) { // Only do parents if no children exist.
1630          $path = preg_split( '![/\\\]!', untrailingslashit( $to ) );
1631          for ( $i = count( $path ); $i >= 0; $i-- ) {
1632              if ( empty( $path[ $i ] ) ) {
1633                  continue;
1634              }
1635  
1636              $dir = implode( '/', array_slice( $path, 0, $i + 1 ) );
1637              if ( preg_match( '!^[a-z]:$!i', $dir ) ) { // Skip it if it looks like a Windows Drive letter.
1638                  continue;
1639              }
1640  
1641              if ( ! $wp_filesystem->is_dir( $dir ) ) {
1642                  $needed_dirs[] = $dir;
1643              } else {
1644                  break; // A folder exists, therefore we don't need to check the levels below this.
1645              }
1646          }
1647      }
1648  
1649      /**
1650       * Filters whether to use ZipArchive to unzip archives.
1651       *
1652       * @since 3.0.0
1653       *
1654       * @param bool $ziparchive Whether to use ZipArchive. Default true.
1655       */
1656      if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
1657          $result = _unzip_file_ziparchive( $file, $to, $needed_dirs );
1658          if ( true === $result ) {
1659              return $result;
1660          } elseif ( is_wp_error( $result ) ) {
1661              if ( 'incompatible_archive' !== $result->get_error_code() ) {
1662                  return $result;
1663              }
1664          }
1665      }
1666      // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
1667      return _unzip_file_pclzip( $file, $to, $needed_dirs );
1668  }
1669  
1670  /**
1671   * Attempts to unzip an archive using the ZipArchive class.
1672   *
1673   * This function should not be called directly, use `unzip_file()` instead.
1674   *
1675   * Assumes that WP_Filesystem() has already been called and set up.
1676   *
1677   * @since 3.0.0
1678   * @access private
1679   *
1680   * @see unzip_file()
1681   *
1682   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1683   *
1684   * @param string   $file        Full path and filename of ZIP archive.
1685   * @param string   $to          Full path on the filesystem to extract archive to.
1686   * @param string[] $needed_dirs A partial list of required folders needed to be created.
1687   * @return true|WP_Error True on success, WP_Error on failure.
1688   */
1689  function _unzip_file_ziparchive( $file, $to, $needed_dirs = array() ) {
1690      global $wp_filesystem;
1691  
1692      $z = new ZipArchive();
1693  
1694      $zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS );
1695  
1696      if ( true !== $zopen ) {
1697          return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) );
1698      }
1699  
1700      $uncompressed_size = 0;
1701  
1702      for ( $i = 0; $i < $z->numFiles; $i++ ) {
1703          $info = $z->statIndex( $i );
1704  
1705          if ( ! $info ) {
1706              $z->close();
1707              return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
1708          }
1709  
1710          if ( str_starts_with( $info['name'], '__MACOSX/' ) ) { // Skip the OS X-created __MACOSX directory.
1711              continue;
1712          }
1713  
1714          // Don't extract invalid files:
1715          if ( 0 !== validate_file( $info['name'] ) ) {
1716              continue;
1717          }
1718  
1719          $uncompressed_size += $info['size'];
1720  
1721          $dirname = dirname( $info['name'] );
1722  
1723          if ( str_ends_with( $info['name'], '/' ) ) {
1724              // Directory.
1725              $needed_dirs[] = $to . untrailingslashit( $info['name'] );
1726          } elseif ( '.' !== $dirname ) {
1727              // Path to a file.
1728              $needed_dirs[] = $to . untrailingslashit( $dirname );
1729          }
1730      }
1731  
1732      // Enough space to unzip the file and copy its contents, with a 10% buffer.
1733      $required_space = $uncompressed_size * 2.1;
1734  
1735      /*
1736       * disk_free_space() could return false. Assume that any falsey value is an error.
1737       * A disk that has zero free bytes has bigger problems.
1738       * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
1739       */
1740      if ( wp_doing_cron() ) {
1741          $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false;
1742  
1743          if ( $available_space && ( $required_space > $available_space ) ) {
1744              $z->close();
1745              return new WP_Error(
1746                  'disk_full_unzip_file',
1747                  __( 'Could not copy files. You may have run out of disk space.' ),
1748                  compact( 'uncompressed_size', 'available_space' )
1749              );
1750          }
1751      }
1752  
1753      $needed_dirs = array_unique( $needed_dirs );
1754  
1755      foreach ( $needed_dirs as $dir ) {
1756          // Check the parent folders of the folders all exist within the creation array.
1757          if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist).
1758              continue;
1759          }
1760  
1761          if ( ! str_contains( $dir, $to ) ) { // If the directory is not within the working directory, skip it.
1762              continue;
1763          }
1764  
1765          $parent_folder = dirname( $dir );
1766  
1767          while ( ! empty( $parent_folder )
1768              && untrailingslashit( $to ) !== $parent_folder
1769              && ! in_array( $parent_folder, $needed_dirs, true )
1770          ) {
1771              $needed_dirs[] = $parent_folder;
1772              $parent_folder = dirname( $parent_folder );
1773          }
1774      }
1775  
1776      asort( $needed_dirs );
1777  
1778      // Create those directories if need be:
1779      foreach ( $needed_dirs as $_dir ) {
1780          // Only check to see if the Dir exists upon creation failure. Less I/O this way.
1781          if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
1782              $z->close();
1783              return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), $_dir );
1784          }
1785      }
1786  
1787      /**
1788       * Filters archive unzipping to override with a custom process.
1789       *
1790       * @since 6.4.0
1791       *
1792       * @param null|true|WP_Error $result         The result of the override. True on success, otherwise WP Error. Default null.
1793       * @param string             $file           Full path and filename of ZIP archive.
1794       * @param string             $to             Full path on the filesystem to extract archive to.
1795       * @param string[]           $needed_dirs    A full list of required folders that need to be created.
1796       * @param float              $required_space The space required to unzip the file and copy its contents, with a 10% buffer.
1797       */
1798      $pre = apply_filters( 'pre_unzip_file', null, $file, $to, $needed_dirs, $required_space );
1799  
1800      if ( null !== $pre ) {
1801          // Ensure the ZIP file archive has been closed.
1802          $z->close();
1803  
1804          return $pre;
1805      }
1806  
1807      for ( $i = 0; $i < $z->numFiles; $i++ ) {
1808          $info = $z->statIndex( $i );
1809  
1810          if ( ! $info ) {
1811              $z->close();
1812              return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
1813          }
1814  
1815          if ( str_ends_with( $info['name'], '/' ) ) { // Directory.
1816              continue;
1817          }
1818  
1819          if ( str_starts_with( $info['name'], '__MACOSX/' ) ) { // Don't extract the OS X-created __MACOSX directory files.
1820              continue;
1821          }
1822  
1823          // Don't extract invalid files:
1824          if ( 0 !== validate_file( $info['name'] ) ) {
1825              continue;
1826          }
1827  
1828          $contents = $z->getFromIndex( $i );
1829  
1830          if ( false === $contents ) {
1831              $z->close();
1832              return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] );
1833          }
1834  
1835          if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE ) ) {
1836              $z->close();
1837              return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] );
1838          }
1839      }
1840  
1841      $z->close();
1842  
1843      /**
1844       * Filters the result of unzipping an archive.
1845       *
1846       * @since 6.4.0
1847       *
1848       * @param true|WP_Error $result         The result of unzipping the archive. True on success, otherwise WP_Error. Default true.
1849       * @param string        $file           Full path and filename of ZIP archive.
1850       * @param string        $to             Full path on the filesystem the archive was extracted to.
1851       * @param string[]      $needed_dirs    A full list of required folders that were created.
1852       * @param float         $required_space The space required to unzip the file and copy its contents, with a 10% buffer.
1853       */
1854      $result = apply_filters( 'unzip_file', true, $file, $to, $needed_dirs, $required_space );
1855  
1856      unset( $needed_dirs );
1857  
1858      return $result;
1859  }
1860  
1861  /**
1862   * Attempts to unzip an archive using the PclZip library.
1863   *
1864   * This function should not be called directly, use `unzip_file()` instead.
1865   *
1866   * Assumes that WP_Filesystem() has already been called and set up.
1867   *
1868   * @since 3.0.0
1869   * @access private
1870   *
1871   * @see unzip_file()
1872   *
1873   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1874   *
1875   * @param string   $file        Full path and filename of ZIP archive.
1876   * @param string   $to          Full path on the filesystem to extract archive to.
1877   * @param string[] $needed_dirs A partial list of required folders needed to be created.
1878   * @return true|WP_Error True on success, WP_Error on failure.
1879   */
1880  function _unzip_file_pclzip( $file, $to, $needed_dirs = array() ) {
1881      global $wp_filesystem;
1882  
1883      mbstring_binary_safe_encoding();
1884  
1885      require_once  ABSPATH . 'wp-admin/includes/class-pclzip.php';
1886  
1887      $archive = new PclZip( $file );
1888  
1889      $archive_files = $archive->extract( PCLZIP_OPT_EXTRACT_AS_STRING );
1890  
1891      reset_mbstring_encoding();
1892  
1893      // Is the archive valid?
1894      if ( ! is_array( $archive_files ) ) {
1895          return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), $archive->errorInfo( true ) );
1896      }
1897  
1898      if ( 0 === count( $archive_files ) ) {
1899          return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) );
1900      }
1901  
1902      $uncompressed_size = 0;
1903  
1904      // Determine any children directories needed (From within the archive).
1905      foreach ( $archive_files as $archive_file ) {
1906          if ( str_starts_with( $archive_file['filename'], '__MACOSX/' ) ) { // Skip the OS X-created __MACOSX directory.
1907              continue;
1908          }
1909  
1910          // Don't extract invalid files:
1911          if ( 0 !== validate_file( $archive_file['filename'] ) ) {
1912              continue;
1913          }
1914  
1915          $uncompressed_size += $archive_file['size'];
1916  
1917          $needed_dirs[] = $to . untrailingslashit( $archive_file['folder'] ? $archive_file['filename'] : dirname( $archive_file['filename'] ) );
1918      }
1919  
1920      // Enough space to unzip the file and copy its contents, with a 10% buffer.
1921      $required_space = $uncompressed_size * 2.1;
1922  
1923      /*
1924       * disk_free_space() could return false. Assume that any falsey value is an error.
1925       * A disk that has zero free bytes has bigger problems.
1926       * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
1927       */
1928      if ( wp_doing_cron() ) {
1929          $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false;
1930  
1931          if ( $available_space && ( $required_space > $available_space ) ) {
1932              return new WP_Error(
1933                  'disk_full_unzip_file',
1934                  __( 'Could not copy files. You may have run out of disk space.' ),
1935                  compact( 'uncompressed_size', 'available_space' )
1936              );
1937          }
1938      }
1939  
1940      $needed_dirs = array_unique( $needed_dirs );
1941  
1942      foreach ( $needed_dirs as $dir ) {
1943          // Check the parent folders of the folders all exist within the creation array.
1944          if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist).
1945              continue;
1946          }
1947  
1948          if ( ! str_contains( $dir, $to ) ) { // If the directory is not within the working directory, skip it.
1949              continue;
1950          }
1951  
1952          $parent_folder = dirname( $dir );
1953  
1954          while ( ! empty( $parent_folder )
1955              && untrailingslashit( $to ) !== $parent_folder
1956              && ! in_array( $parent_folder, $needed_dirs, true )
1957          ) {
1958              $needed_dirs[] = $parent_folder;
1959              $parent_folder = dirname( $parent_folder );
1960          }
1961      }
1962  
1963      asort( $needed_dirs );
1964  
1965      // Create those directories if need be:
1966      foreach ( $needed_dirs as $_dir ) {
1967          // Only check to see if the dir exists upon creation failure. Less I/O this way.
1968          if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
1969              return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), $_dir );
1970          }
1971      }
1972  
1973      /** This filter is documented in wp-admin/includes/file.php */
1974      $pre = apply_filters( 'pre_unzip_file', null, $file, $to, $needed_dirs, $required_space );
1975  
1976      if ( null !== $pre ) {
1977          return $pre;
1978      }
1979  
1980      // Extract the files from the zip.
1981      foreach ( $archive_files as $archive_file ) {
1982          if ( $archive_file['folder'] ) {
1983              continue;
1984          }
1985  
1986          if ( str_starts_with( $archive_file['filename'], '__MACOSX/' ) ) { // Don't extract the OS X-created __MACOSX directory files.
1987              continue;
1988          }
1989  
1990          // Don't extract invalid files:
1991          if ( 0 !== validate_file( $archive_file['filename'] ) ) {
1992              continue;
1993          }
1994  
1995          if ( ! $wp_filesystem->put_contents( $to . $archive_file['filename'], $archive_file['content'], FS_CHMOD_FILE ) ) {
1996              return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $archive_file['filename'] );
1997          }
1998      }
1999  
2000      /** This filter is documented in wp-admin/includes/file.php */
2001      $result = apply_filters( 'unzip_file', true, $file, $to, $needed_dirs, $required_space );
2002  
2003      unset( $needed_dirs );
2004  
2005      return $result;
2006  }
2007  
2008  /**
2009   * Copies a directory from one location to another via the WordPress Filesystem
2010   * Abstraction.
2011   *
2012   * Assumes that WP_Filesystem() has already been called and setup.
2013   *
2014   * @since 2.5.0
2015   *
2016   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
2017   *
2018   * @param string   $from      Source directory.
2019   * @param string   $to        Destination directory.
2020   * @param string[] $skip_list An array of files/folders to skip copying.
2021   * @return true|WP_Error True on success, WP_Error on failure.
2022   */
2023  function copy_dir( $from, $to, $skip_list = array() ) {
2024      global $wp_filesystem;
2025  
2026      $dirlist = $wp_filesystem->dirlist( $from );
2027  
2028      if ( false === $dirlist ) {
2029          return new WP_Error( 'dirlist_failed_copy_dir', __( 'Directory listing failed.' ), basename( $from ) );
2030      }
2031  
2032      $from = trailingslashit( $from );
2033      $to   = trailingslashit( $to );
2034  
2035      if ( ! $wp_filesystem->exists( $to ) && ! $wp_filesystem->mkdir( $to ) ) {
2036          return new WP_Error(
2037              'mkdir_destination_failed_copy_dir',
2038              __( 'Could not create the destination directory.' ),
2039              basename( $to )
2040          );
2041      }
2042  
2043      foreach ( (array) $dirlist as $filename => $fileinfo ) {
2044          if ( in_array( $filename, $skip_list, true ) ) {
2045              continue;
2046          }
2047  
2048          if ( 'f' === $fileinfo['type'] ) {
2049              if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) {
2050                  // If copy failed, chmod file to 0644 and try again.
2051                  $wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE );
2052  
2053                  if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) {
2054                      return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename );
2055                  }
2056              }
2057  
2058              wp_opcache_invalidate( $to . $filename );
2059          } elseif ( 'd' === $fileinfo['type'] ) {
2060              if ( ! $wp_filesystem->is_dir( $to . $filename ) ) {
2061                  if ( ! $wp_filesystem->mkdir( $to . $filename, FS_CHMOD_DIR ) ) {
2062                      return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename );
2063                  }
2064              }
2065  
2066              // Generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list.
2067              $sub_skip_list = array();
2068  
2069              foreach ( $skip_list as $skip_item ) {
2070                  if ( str_starts_with( $skip_item, $filename . '/' ) ) {
2071                      $sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item );
2072                  }
2073              }
2074  
2075              $result = copy_dir( $from . $filename, $to . $filename, $sub_skip_list );
2076  
2077              if ( is_wp_error( $result ) ) {
2078                  return $result;
2079              }
2080          }
2081      }
2082  
2083      return true;
2084  }
2085  
2086  /**
2087   * Moves a directory from one location to another.
2088   *
2089   * Recursively invalidates OPcache on success.
2090   *
2091   * If the renaming failed, falls back to copy_dir().
2092   *
2093   * Assumes that WP_Filesystem() has already been called and setup.
2094   *
2095   * This function is not designed to merge directories, copy_dir() should be used instead.
2096   *
2097   * @since 6.2.0
2098   *
2099   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
2100   *
2101   * @param string $from      Source directory.
2102   * @param string $to        Destination directory.
2103   * @param bool   $overwrite Optional. Whether to overwrite the destination directory if it exists.
2104   *                          Default false.
2105   * @return true|WP_Error True on success, WP_Error on failure.
2106   */
2107  function move_dir( $from, $to, $overwrite = false ) {
2108      global $wp_filesystem;
2109  
2110      if ( trailingslashit( strtolower( $from ) ) === trailingslashit( strtolower( $to ) ) ) {
2111          return new WP_Error( 'source_destination_same_move_dir', __( 'The source and destination are the same.' ) );
2112      }
2113  
2114      if ( $wp_filesystem->exists( $to ) ) {
2115          if ( ! $overwrite ) {
2116              return new WP_Error( 'destination_already_exists_move_dir', __( 'The destination folder already exists.' ), $to );
2117          } elseif ( ! $wp_filesystem->delete( $to, true ) ) {
2118              // Can't overwrite if the destination couldn't be deleted.
2119              return new WP_Error( 'destination_not_deleted_move_dir', __( 'The destination directory already exists and could not be removed.' ) );
2120          }
2121      }
2122  
2123      if ( $wp_filesystem->move( $from, $to ) ) {
2124          /*
2125           * When using an environment with shared folders,
2126           * there is a delay in updating the filesystem's cache.
2127           *
2128           * This is a known issue in environments with a VirtualBox provider.
2129           *
2130           * A 200ms delay gives time for the filesystem to update its cache,
2131           * prevents "Operation not permitted", and "No such file or directory" warnings.
2132           *
2133           * This delay is used in other projects, including Composer.
2134           * @link https://github.com/composer/composer/blob/2.5.1/src/Composer/Util/Platform.php#L228-L233
2135           */
2136          usleep( 200000 );
2137          wp_opcache_invalidate_directory( $to );
2138  
2139          return true;
2140      }
2141  
2142      // Fall back to a recursive copy.
2143      if ( ! $wp_filesystem->is_dir( $to ) ) {
2144          if ( ! $wp_filesystem->mkdir( $to, FS_CHMOD_DIR ) ) {
2145              return new WP_Error( 'mkdir_failed_move_dir', __( 'Could not create directory.' ), $to );
2146          }
2147      }
2148  
2149      $result = copy_dir( $from, $to, array( basename( $to ) ) );
2150  
2151      // Clear the source directory.
2152      if ( true === $result ) {
2153          $wp_filesystem->delete( $from, true );
2154      }
2155  
2156      return $result;
2157  }
2158  
2159  /**
2160   * Initializes and connects the WordPress Filesystem Abstraction classes.
2161   *
2162   * This function will include the chosen transport and attempt connecting.
2163   *
2164   * Plugins may add extra transports, And force WordPress to use them by returning
2165   * the filename via the {@see 'filesystem_method_file'} filter.
2166   *
2167   * @since 2.5.0
2168   *
2169   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
2170   *
2171   * @param array|false  $args                         Optional. Connection args, These are passed
2172   *                                                   directly to the `WP_Filesystem_*()` classes.
2173   *                                                   Default false.
2174   * @param string|false $context                      Optional. Context for get_filesystem_method().
2175   *                                                   Default false.
2176   * @param bool         $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
2177   *                                                   Default false.
2178   * @return bool|null True on success, false on failure,
2179   *                   null if the filesystem method class file does not exist.
2180   */
2181  function WP_Filesystem( $args = false, $context = false, $allow_relaxed_file_ownership = false ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
2182      global $wp_filesystem;
2183  
2184      require_once  ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php';
2185  
2186      $method = get_filesystem_method( $args, $context, $allow_relaxed_file_ownership );
2187  
2188      if ( ! $method ) {
2189          return false;
2190      }
2191  
2192      if ( ! class_exists( "WP_Filesystem_$method" ) ) {
2193  
2194          /**
2195           * Filters the path for a specific filesystem method class file.
2196           *
2197           * @since 2.6.0
2198           *
2199           * @see get_filesystem_method()
2200           *
2201           * @param string $path   Path to the specific filesystem method class file.
2202           * @param string $method The filesystem method to use.
2203           */
2204          $abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method );
2205  
2206          if ( ! file_exists( $abstraction_file ) ) {
2207              return null;
2208          }
2209  
2210          require_once $abstraction_file;
2211      }
2212      $method = "WP_Filesystem_$method";
2213  
2214      $wp_filesystem = new $method( $args );
2215  
2216      /*
2217       * Define the timeouts for the connections. Only available after the constructor is called
2218       * to allow for per-transport overriding of the default.
2219       */
2220      if ( ! defined( 'FS_CONNECT_TIMEOUT' ) ) {
2221          define( 'FS_CONNECT_TIMEOUT', 30 ); // 30 seconds.
2222      }
2223      if ( ! defined( 'FS_TIMEOUT' ) ) {
2224          define( 'FS_TIMEOUT', 30 ); // 30 seconds.
2225      }
2226  
2227      if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
2228          return false;
2229      }
2230  
2231      if ( ! $wp_filesystem->connect() ) {
2232          return false; // There was an error connecting to the server.
2233      }
2234  
2235      // Set the permission constants if not already set.
2236      if ( ! defined( 'FS_CHMOD_DIR' ) ) {
2237          define( 'FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
2238      }
2239      if ( ! defined( 'FS_CHMOD_FILE' ) ) {
2240          define( 'FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
2241      }
2242  
2243      return true;
2244  }
2245  
2246  /**
2247   * Determines which method to use for reading, writing, modifying, or deleting
2248   * files on the filesystem.
2249   *
2250   * The priority of the transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets
2251   * (Via Sockets class, or `fsockopen()`). Valid values for these are: 'direct', 'ssh2',
2252   * 'ftpext' or 'ftpsockets'.
2253   *
2254   * The return value can be overridden by defining the `FS_METHOD` constant in `wp-config.php`,
2255   * or filtering via {@see 'filesystem_method'}.
2256   *
2257   * @link https://developer.wordpress.org/advanced-administration/wordpress/wp-config/#wordpress-upgrade-constants
2258   *
2259   * Plugins may define a custom transport handler, See WP_Filesystem().
2260   *
2261   * @since 2.5.0
2262   *
2263   * @global callable $_wp_filesystem_direct_method
2264   *
2265   * @param array  $args                         Optional. Connection details. Default empty array.
2266   * @param string $context                      Optional. Full path to the directory that is tested
2267   *                                             for being writable. Default empty.
2268   * @param bool   $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
2269   *                                             Default false.
2270   * @return string The transport to use, see description for valid return values.
2271   */
2272  function get_filesystem_method( $args = array(), $context = '', $allow_relaxed_file_ownership = false ) {
2273      // Please ensure that this is either 'direct', 'ssh2', 'ftpext', or 'ftpsockets'.
2274      $method = defined( 'FS_METHOD' ) ? FS_METHOD : false;
2275  
2276      if ( ! $context ) {
2277          $context = WP_CONTENT_DIR;
2278      }
2279  
2280      // If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it.
2281      if ( WP_LANG_DIR === $context && ! is_dir( $context ) ) {
2282          $context = dirname( $context );
2283      }
2284  
2285      $context = trailingslashit( $context );
2286  
2287      if ( ! $method ) {
2288  
2289          $temp_file_name = $context . 'temp-write-test-' . str_replace( '.', '-', uniqid( '', true ) );
2290          $temp_handle    = @fopen( $temp_file_name, 'w' );
2291          if ( $temp_handle ) {
2292  
2293              // Attempt to determine the file owner of the WordPress files, and that of newly created files.
2294              $wp_file_owner   = false;
2295              $temp_file_owner = false;
2296              if ( function_exists( 'fileowner' ) ) {
2297                  $wp_file_owner   = @fileowner( __FILE__ );
2298                  $temp_file_owner = @fileowner( $temp_file_name );
2299              }
2300  
2301              if ( false !== $wp_file_owner && $wp_file_owner === $temp_file_owner ) {
2302                  /*
2303                   * WordPress is creating files as the same owner as the WordPress files,
2304                   * this means it's safe to modify & create new files via PHP.
2305                   */
2306                  $method                                  = 'direct';
2307                  $GLOBALS['_wp_filesystem_direct_method'] = 'file_owner';
2308              } elseif ( $allow_relaxed_file_ownership ) {
2309                  /*
2310                   * The $context directory is writable, and $allow_relaxed_file_ownership is set,
2311                   * this means we can modify files safely in this directory.
2312                   * This mode doesn't create new files, only alter existing ones.
2313                   */
2314                  $method                                  = 'direct';
2315                  $GLOBALS['_wp_filesystem_direct_method'] = 'relaxed_ownership';
2316              }
2317  
2318              fclose( $temp_handle );
2319              @unlink( $temp_file_name );
2320          }
2321      }
2322  
2323      if ( ! $method && isset( $args['connection_type'] ) && 'ssh' === $args['connection_type'] && extension_loaded( 'ssh2' ) ) {
2324          $method = 'ssh2';
2325      }
2326      if ( ! $method && extension_loaded( 'ftp' ) ) {
2327          $method = 'ftpext';
2328      }
2329      if ( ! $method && ( extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) ) {
2330          $method = 'ftpsockets'; // Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread.
2331      }
2332  
2333      /**
2334       * Filters the filesystem method to use.
2335       *
2336       * @since 2.6.0
2337       *
2338       * @param string $method                       Filesystem method to return.
2339       * @param array  $args                         An array of connection details for the method.
2340       * @param string $context                      Full path to the directory that is tested for being writable.
2341       * @param bool   $allow_relaxed_file_ownership Whether to allow Group/World writable.
2342       */
2343      return apply_filters( 'filesystem_method', $method, $args, $context, $allow_relaxed_file_ownership );
2344  }
2345  
2346  /**
2347   * Displays a form to the user to request for their FTP/SSH details in order
2348   * to connect to the filesystem.
2349   *
2350   * All chosen/entered details are saved, excluding the password.
2351   *
2352   * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467)
2353   * to specify an alternate FTP/SSH port.
2354   *
2355   * Plugins may override this form by returning true|false via the {@see 'request_filesystem_credentials'} filter.
2356   *
2357   * @since 2.5.0
2358   * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
2359   *
2360   * @global string $pagenow The filename of the current screen.
2361   *
2362   * @param string        $form_post                    The URL to post the form to.
2363   * @param string        $type                         Optional. Chosen type of filesystem. Default empty.
2364   * @param bool|WP_Error $error                        Optional. Whether the current request has failed
2365   *                                                    to connect, or an error object. Default false.
2366   * @param string        $context                      Optional. Full path to the directory that is tested
2367   *                                                    for being writable. Default empty.
2368   * @param array         $extra_fields                 Optional. Extra `POST` fields to be checked
2369   *                                                    for inclusion in the post. Default null.
2370   * @param bool          $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
2371   *                                                    Default false.
2372   * @return bool|array True if no filesystem credentials are required,
2373   *                    false if they are required but have not been provided,
2374   *                    array of credentials if they are required and have been provided.
2375   */
2376  function request_filesystem_credentials( $form_post, $type = '', $error = false, $context = '', $extra_fields = null, $allow_relaxed_file_ownership = false ) {
2377      global $pagenow;
2378  
2379      /**
2380       * Filters the filesystem credentials.
2381       *
2382       * Returning anything other than an empty string will effectively short-circuit
2383       * output of the filesystem credentials form, returning that value instead.
2384       *
2385       * A filter should return true if no filesystem credentials are required, false if they are required but have not been
2386       * provided, or an array of credentials if they are required and have been provided.
2387       *
2388       * @since 2.5.0
2389       * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
2390       *
2391       * @param mixed         $credentials                  Credentials to return instead. Default empty string.
2392       * @param string        $form_post                    The URL to post the form to.
2393       * @param string        $type                         Chosen type of filesystem.
2394       * @param bool|WP_Error $error                        Whether the current request has failed to connect,
2395       *                                                    or an error object.
2396       * @param string        $context                      Full path to the directory that is tested for
2397       *                                                    being writable.
2398       * @param array         $extra_fields                 Extra POST fields.
2399       * @param bool          $allow_relaxed_file_ownership Whether to allow Group/World writable.
2400       */
2401      $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields, $allow_relaxed_file_ownership );
2402  
2403      if ( '' !== $req_cred ) {
2404          return $req_cred;
2405      }
2406  
2407      if ( empty( $type ) ) {
2408          $type = get_filesystem_method( array(), $context, $allow_relaxed_file_ownership );
2409      }
2410  
2411      if ( 'direct' === $type ) {
2412          return true;
2413      }
2414  
2415      if ( is_null( $extra_fields ) ) {
2416          $extra_fields = array( 'version', 'locale' );
2417      }
2418  
2419      $credentials = get_option(
2420          'ftp_credentials',
2421          array(
2422              'hostname' => '',
2423              'username' => '',
2424          )
2425      );
2426  
2427      $submitted_form = wp_unslash( $_POST );
2428  
2429      // Verify nonce, or unset submitted form field values on failure.
2430      if ( ! isset( $_POST['_fs_nonce'] ) || ! wp_verify_nonce( $_POST['_fs_nonce'], 'filesystem-credentials' ) ) {
2431          unset(
2432              $submitted_form['hostname'],
2433              $submitted_form['username'],
2434              $submitted_form['password'],
2435              $submitted_form['public_key'],
2436              $submitted_form['private_key'],
2437              $submitted_form['connection_type']
2438          );
2439      }
2440  
2441      $ftp_constants = array(
2442          'hostname'    => 'FTP_HOST',
2443          'username'    => 'FTP_USER',
2444          'password'    => 'FTP_PASS',
2445          'public_key'  => 'FTP_PUBKEY',
2446          'private_key' => 'FTP_PRIKEY',
2447      );
2448  
2449      /*
2450       * If defined, set it to that. Else, if POST'd, set it to that. If not, set it to an empty string.
2451       * Otherwise, keep it as it previously was (saved details in option).
2452       */
2453      foreach ( $ftp_constants as $key => $constant ) {
2454          if ( defined( $constant ) ) {
2455              $credentials[ $key ] = constant( $constant );
2456          } elseif ( ! empty( $submitted_form[ $key ] ) ) {
2457              $credentials[ $key ] = $submitted_form[ $key ];
2458          } elseif ( ! isset( $credentials[ $key ] ) ) {
2459              $credentials[ $key ] = '';
2460          }
2461      }
2462  
2463      // Sanitize the hostname, some people might pass in odd data.
2464      $credentials['hostname'] = preg_replace( '|\w+://|', '', $credentials['hostname'] ); // Strip any schemes off.
2465  
2466      if ( strpos( $credentials['hostname'], ':' ) ) {
2467          list( $credentials['hostname'], $credentials['port'] ) = explode( ':', $credentials['hostname'], 2 );
2468          if ( ! is_numeric( $credentials['port'] ) ) {
2469              unset( $credentials['port'] );
2470          }
2471      } else {
2472          unset( $credentials['port'] );
2473      }
2474  
2475      if ( ( defined( 'FTP_SSH' ) && FTP_SSH ) || ( defined( 'FS_METHOD' ) && 'ssh2' === FS_METHOD ) ) {
2476          $credentials['connection_type'] = 'ssh';
2477      } elseif ( ( defined( 'FTP_SSL' ) && FTP_SSL ) && 'ftpext' === $type ) { // Only the FTP Extension understands SSL.
2478          $credentials['connection_type'] = 'ftps';
2479      } elseif ( ! empty( $submitted_form['connection_type'] ) ) {
2480          $credentials['connection_type'] = $submitted_form['connection_type'];
2481      } elseif ( ! isset( $credentials['connection_type'] ) ) { // All else fails (and it's not defaulted to something else saved), default to FTP.
2482          $credentials['connection_type'] = 'ftp';
2483      }
2484  
2485      if ( ! $error
2486          && ( ! empty( $credentials['hostname'] ) && ! empty( $credentials['username'] ) && ! empty( $credentials['password'] )
2487              || 'ssh' === $credentials['connection_type'] && ! empty( $credentials['public_key'] ) && ! empty( $credentials['private_key'] )
2488          )
2489      ) {
2490          $stored_credentials = $credentials;
2491  
2492          if ( ! empty( $stored_credentials['port'] ) ) { // Save port as part of hostname to simplify above code.
2493              $stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
2494          }
2495  
2496          unset(
2497              $stored_credentials['password'],
2498              $stored_credentials['port'],
2499              $stored_credentials['private_key'],
2500              $stored_credentials['public_key']
2501          );
2502  
2503          if ( ! wp_installing() ) {
2504              update_option( 'ftp_credentials', $stored_credentials, false );
2505          }
2506  
2507          return $credentials;
2508      }
2509  
2510      $hostname        = $credentials['hostname'] ?? '';
2511      $username        = $credentials['username'] ?? '';
2512      $public_key      = $credentials['public_key'] ?? '';
2513      $private_key     = $credentials['private_key'] ?? '';
2514      $port            = $credentials['port'] ?? '';
2515      $connection_type = $credentials['connection_type'] ?? '';
2516  
2517      if ( $error ) {
2518          $error_string = __( '<strong>Error:</strong> Could not connect to the server. Please verify the settings are correct.' );
2519          if ( is_wp_error( $error ) ) {
2520              $error_string = esc_html( $error->get_error_message() );
2521          }
2522          wp_admin_notice(
2523              $error_string,
2524              array(
2525                  'id'                 => 'message',
2526                  'additional_classes' => array( 'error' ),
2527              )
2528          );
2529      }
2530  
2531      $types = array();
2532      if ( extension_loaded( 'ftp' ) || extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) {
2533          $types['ftp'] = __( 'FTP' );
2534      }
2535      if ( extension_loaded( 'ftp' ) ) { // Only this supports FTPS.
2536          $types['ftps'] = __( 'FTPS (SSL)' );
2537      }
2538      if ( extension_loaded( 'ssh2' ) ) {
2539          $types['ssh'] = __( 'SSH2' );
2540      }
2541  
2542      /**
2543       * Filters the connection types to output to the filesystem credentials form.
2544       *
2545       * @since 2.9.0
2546       * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
2547       *
2548       * @param string[]      $types       Types of connections.
2549       * @param array         $credentials Credentials to connect with.
2550       * @param string        $type        Chosen filesystem method.
2551       * @param bool|WP_Error $error       Whether the current request has failed to connect,
2552       *                                   or an error object.
2553       * @param string        $context     Full path to the directory that is tested for being writable.
2554       */
2555      $types = apply_filters( 'fs_ftp_connection_types', $types, $credentials, $type, $error, $context );
2556      ?>
2557  <form action="<?php echo esc_url( $form_post ); ?>" method="post">
2558  <div id="request-filesystem-credentials-form" class="request-filesystem-credentials-form">
2559      <?php
2560      // Print a H1 heading in the FTP credentials modal dialog, default is a H2.
2561      $heading_tag = 'h2';
2562      if ( 'plugins.php' === $pagenow || 'plugin-install.php' === $pagenow ) {
2563          $heading_tag = 'h1';
2564      }
2565      echo "<$heading_tag id='request-filesystem-credentials-title'>" . __( 'Connection Information' ) . "</$heading_tag>";
2566      ?>
2567  <p id="request-filesystem-credentials-desc">
2568      <?php
2569      $label_user = __( 'Username' );
2570      $label_pass = __( 'Password' );
2571      _e( 'To perform the requested action, WordPress needs to access your web server.' );
2572      echo ' ';
2573      if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) {
2574          if ( isset( $types['ssh'] ) ) {
2575              _e( 'Please enter your FTP or SSH credentials to proceed.' );
2576              $label_user = __( 'FTP/SSH Username' );
2577              $label_pass = __( 'FTP/SSH Password' );
2578          } else {
2579              _e( 'Please enter your FTP credentials to proceed.' );
2580              $label_user = __( 'FTP Username' );
2581              $label_pass = __( 'FTP Password' );
2582          }
2583          echo ' ';
2584      }
2585      _e( 'If you do not remember your credentials, you should contact your web host.' );
2586  
2587      $hostname_value = esc_attr( $hostname );
2588      if ( ! empty( $port ) ) {
2589          $hostname_value .= ":$port";
2590      }
2591  
2592      $password_value = '';
2593      if ( defined( 'FTP_PASS' ) ) {
2594          $password_value = '*****';
2595      }
2596      ?>
2597  </p>
2598  <label for="hostname">
2599      <span class="field-title"><?php _e( 'Hostname' ); ?></span>
2600      <input name="hostname" type="text" id="hostname" aria-describedby="request-filesystem-credentials-desc" class="code" placeholder="<?php esc_attr_e( 'example: www.wordpress.org' ); ?>" value="<?php echo $hostname_value; ?>"<?php disabled( defined( 'FTP_HOST' ) ); ?> />
2601  </label>
2602  <div class="ftp-username">
2603      <label for="username">
2604          <span class="field-title"><?php echo $label_user; ?></span>
2605          <input name="username" type="text" id="username" value="<?php echo esc_attr( $username ); ?>"<?php disabled( defined( 'FTP_USER' ) ); ?> />
2606      </label>
2607  </div>
2608  <div class="ftp-password">
2609      <label for="password">
2610          <span class="field-title"><?php echo $label_pass; ?></span>
2611          <input name="password" type="password" id="password" value="<?php echo $password_value; ?>"<?php disabled( defined( 'FTP_PASS' ) ); ?> spellcheck="false" />
2612          <?php
2613          if ( ! defined( 'FTP_PASS' ) ) {
2614              _e( 'This password will not be stored on the server.' );
2615          }
2616          ?>
2617      </label>
2618  </div>
2619  <fieldset>
2620  <legend><?php _e( 'Connection Type' ); ?></legend>
2621      <?php
2622      $disabled = disabled( ( defined( 'FTP_SSL' ) && FTP_SSL ) || ( defined( 'FTP_SSH' ) && FTP_SSH ), true, false );
2623      foreach ( $types as $name => $text ) :
2624          ?>
2625      <label for="<?php echo esc_attr( $name ); ?>">
2626          <input type="radio" name="connection_type" id="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $name ); ?>" <?php checked( $name, $connection_type ); ?> <?php echo $disabled; ?> />
2627          <?php echo $text; ?>
2628      </label>
2629          <?php
2630      endforeach;
2631      ?>
2632  </fieldset>
2633      <?php
2634      if ( isset( $types['ssh'] ) ) {
2635          $hidden_class = '';
2636          if ( 'ssh' !== $connection_type ) {
2637              $hidden_class = ' class="hidden"';
2638          }
2639          ?>
2640  <fieldset id="ssh-keys"<?php echo $hidden_class; ?>>
2641  <legend><?php _e( 'Authentication Keys' ); ?></legend>
2642  <label for="public_key">
2643      <span class="field-title"><?php _e( 'Public Key:' ); ?></span>
2644      <input name="public_key" type="text" id="public_key" aria-describedby="auth-keys-desc" value="<?php echo esc_attr( $public_key ); ?>"<?php disabled( defined( 'FTP_PUBKEY' ) ); ?> />
2645  </label>
2646  <label for="private_key">
2647      <span class="field-title"><?php _e( 'Private Key:' ); ?></span>
2648      <input name="private_key" type="text" id="private_key" value="<?php echo esc_attr( $private_key ); ?>"<?php disabled( defined( 'FTP_PRIKEY' ) ); ?> />
2649  </label>
2650  <p id="auth-keys-desc"><?php _e( 'Enter the location on the server where the public and private keys are located. If a passphrase is needed, enter that in the password field above.' ); ?></p>
2651  </fieldset>
2652          <?php
2653      }
2654  
2655      foreach ( (array) $extra_fields as $field ) {
2656          if ( isset( $submitted_form[ $field ] ) ) {
2657              echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( $submitted_form[ $field ] ) . '" />';
2658          }
2659      }
2660  
2661      /*
2662       * Make sure the `submit_button()` function is available during the REST API call
2663       * from WP_Site_Health_Auto_Updates::test_check_wp_filesystem_method().
2664       */
2665      if ( ! function_exists( 'submit_button' ) ) {
2666          require_once  ABSPATH . 'wp-admin/includes/template.php';
2667      }
2668      ?>
2669      <p class="request-filesystem-credentials-action-buttons">
2670          <?php wp_nonce_field( 'filesystem-credentials', '_fs_nonce', false, true ); ?>
2671          <button class="button cancel-button" data-js-action="close" type="button"><?php _e( 'Cancel' ); ?></button>
2672          <?php submit_button( __( 'Proceed' ), 'primary', 'upgrade', false ); ?>
2673      </p>
2674  </div>
2675  </form>
2676      <?php
2677      return false;
2678  }
2679  
2680  /**
2681   * Prints the filesystem credentials modal when needed.
2682   *
2683   * @since 4.2.0
2684   */
2685  function wp_print_request_filesystem_credentials_modal() {
2686      $filesystem_method = get_filesystem_method();
2687  
2688      ob_start();
2689      $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
2690      ob_end_clean();
2691  
2692      $request_filesystem_credentials = ( 'direct' !== $filesystem_method && ! $filesystem_credentials_are_stored );
2693      if ( ! $request_filesystem_credentials ) {
2694          return;
2695      }
2696      ?>
2697      <div id="request-filesystem-credentials-dialog" class="notification-dialog-wrap request-filesystem-credentials-dialog">
2698          <div class="notification-dialog-background"></div>
2699          <div class="notification-dialog" role="dialog" aria-labelledby="request-filesystem-credentials-title" tabindex="0">
2700              <div class="request-filesystem-credentials-dialog-content">
2701                  <?php request_filesystem_credentials( site_url() ); ?>
2702              </div>
2703          </div>
2704      </div>
2705      <?php
2706  }
2707  
2708  /**
2709   * Attempts to clear the opcode cache for an individual PHP file.
2710   *
2711   * This function can be called safely without having to check the file extension
2712   * or availability of the OPcache extension.
2713   *
2714   * Whether or not invalidation is possible is cached to improve performance.
2715   *
2716   * @since 5.5.0
2717   *
2718   * @link https://www.php.net/manual/en/function.opcache-invalidate.php
2719   *
2720   * @param string $filepath Path to the file, including extension, for which the opcode cache is to be cleared.
2721   * @param bool   $force    Invalidate even if the modification time is not newer than the file in cache.
2722   *                         Default false.
2723   * @return bool True if opcache was invalidated for `$filepath`, or there was nothing to invalidate.
2724   *              False if opcache invalidation is not available, or is disabled via filter.
2725   */
2726  function wp_opcache_invalidate( $filepath, $force = false ) {
2727      static $can_invalidate = null;
2728  
2729      /*
2730       * Check to see if WordPress is able to run `opcache_invalidate()` or not, and cache the value.
2731       *
2732       * First, check to see if the function is available to call, then if the host has restricted
2733       * the ability to run the function to avoid a PHP warning.
2734       *
2735       * `opcache.restrict_api` can specify the path for files allowed to call `opcache_invalidate()`.
2736       *
2737       * If the host has this set, check whether the path in `opcache.restrict_api` matches
2738       * the beginning of the path of the origin file.
2739       *
2740       * `$_SERVER['SCRIPT_FILENAME']` approximates the origin file's path, but `realpath()`
2741       * is necessary because `SCRIPT_FILENAME` can be a relative path when run from CLI.
2742       *
2743       * For more details, see:
2744       * - https://www.php.net/manual/en/opcache.configuration.php
2745       * - https://www.php.net/manual/en/reserved.variables.server.php
2746       * - https://core.trac.wordpress.org/ticket/36455
2747       */
2748      if ( null === $can_invalidate
2749          && function_exists( 'opcache_invalidate' )
2750          && ( ! ini_get( 'opcache.restrict_api' )
2751              || stripos( realpath( $_SERVER['SCRIPT_FILENAME'] ), ini_get( 'opcache.restrict_api' ) ) === 0 )
2752      ) {
2753          $can_invalidate = true;
2754      }
2755  
2756      // If invalidation is not available, return early.
2757      if ( ! $can_invalidate ) {
2758          return false;
2759      }
2760  
2761      // Verify that file to be invalidated has a PHP extension.
2762      if ( '.php' !== strtolower( substr( $filepath, -4 ) ) ) {
2763          return false;
2764      }
2765  
2766      /**
2767       * Filters whether to invalidate a file from the opcode cache.
2768       *
2769       * @since 5.5.0
2770       *
2771       * @param bool   $will_invalidate Whether WordPress will invalidate `$filepath`. Default true.
2772       * @param string $filepath        The path to the PHP file to invalidate.
2773       */
2774      if ( apply_filters( 'wp_opcache_invalidate_file', true, $filepath ) ) {
2775          return opcache_invalidate( $filepath, $force );
2776      }
2777  
2778      return false;
2779  }
2780  
2781  /**
2782   * Attempts to clear the opcode cache for a directory of files.
2783   *
2784   * @since 6.2.0
2785   *
2786   * @see wp_opcache_invalidate()
2787   * @link https://www.php.net/manual/en/function.opcache-invalidate.php
2788   *
2789   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
2790   *
2791   * @param string $dir The path to the directory for which the opcode cache is to be cleared.
2792   */
2793  function wp_opcache_invalidate_directory( $dir ) {
2794      global $wp_filesystem;
2795  
2796      if ( ! is_string( $dir ) || '' === trim( $dir ) ) {
2797          if ( WP_DEBUG ) {
2798              $error_message = sprintf(
2799                  /* translators: %s: The function name. */
2800                  __( '%s expects a non-empty string.' ),
2801                  '<code>wp_opcache_invalidate_directory()</code>'
2802              );
2803              wp_trigger_error( '', $error_message );
2804          }
2805          return;
2806      }
2807  
2808      $dirlist = $wp_filesystem->dirlist( $dir, false, true );
2809  
2810      if ( empty( $dirlist ) ) {
2811          return;
2812      }
2813  
2814      /*
2815       * Recursively invalidate opcache of files in a directory.
2816       *
2817       * WP_Filesystem_*::dirlist() returns an array of file and directory information.
2818       *
2819       * This does not include a path to the file or directory.
2820       * To invalidate files within sub-directories, recursion is needed
2821       * to prepend an absolute path containing the sub-directory's name.
2822       *
2823       * @param array  $dirlist Array of file/directory information from WP_Filesystem_Base::dirlist(),
2824       *                        with sub-directories represented as nested arrays.
2825       * @param string $path    Absolute path to the directory.
2826       */
2827      $invalidate_directory = static function ( $dirlist, $path ) use ( &$invalidate_directory ) {
2828          $path = trailingslashit( $path );
2829  
2830          foreach ( $dirlist as $name => $details ) {
2831              if ( 'f' === $details['type'] ) {
2832                  wp_opcache_invalidate( $path . $name, true );
2833              } elseif ( is_array( $details['files'] ) && ! empty( $details['files'] ) ) {
2834                  $invalidate_directory( $details['files'], $path . $name );
2835              }
2836          }
2837      };
2838  
2839      $invalidate_directory( $dirlist, $dir );
2840  }


Generated : Tue Sep 15 08:20:32 2026 Cross-referenced by PHPXref