[ Index ]

PHP Cross Reference of WordPress

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


Generated: Mon Aug 2 01:00:04 2021 Cross-referenced by PHPXref 0.7.1